I am working on a project with user authentication using auth.js in next.js. I want to have an API that get's specific information about the user from a MongoDB Database.
The site is secured via the middleware in next.js. My API works if i directly access the URL after logging in (localhost:3000/api/Project).
When I try to fetch the data though, I get an error Error: Unexpected token '<', "<!DOCTYPE "... is not valid JSON so there seems to be a redirect somewhere but I can' figure out why.
This is my api/Projects/route.js
import { connectDB } from "../../../utils/database";
import { NextResponse } from "next/server";
import Project from "../../(models)/Project";
import { getServerSession } from "next-auth";
import { options } from "../../api/auth/[...nextauth]/options";
export const GET = async (req, res) => {
const session = await getServerSession(options);
try {
await connectDB();
const fetchedProjects = await Project.find({
userID: session.user.id,
}).exec();
return new NextResponse(JSON.stringify(fetchedProjects), { status: 200 });
} catch (error) {
return new NextResponse("Error in fetching data" + error, { status: 500 });
}
};
This is the api fetch in my app/projects/page.js
async function getProjects() {
try {
console.log("FETCHING DOCUMENTS");
const res = await fetch("http://localhost:3000/api/Projects", {
cache: "no-store",
});
if (!res.ok) return notFound();
console.log(res);
return res.json();
} catch (error) {
console.log(error);
}
};
If I bypass all my authentication and just fetch all entries from the database in my API this code works. With the authentication in place fetch returns the following (taken from the console):

http://localhost:3000/api/Project, nothttp://localhost:3000/api/Projectsin yourfetchProjects, so thefetchurl is correct. I updated the question.