2

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): console screenshot

2
  • It's http://localhost:3000/api/Project, not http://localhost:3000/api/Projects in your fetch Commented Feb 23, 2024 at 16:33
  • My bad had a typo in my question. The folder is indeed Projects, so the fetch url is correct. I updated the question. Commented Feb 24, 2024 at 7:06

1 Answer 1

2

I assume that's because after you log in on the browser, some sessions are being stored and sent with your request. However, the same thing isn't true in your Server Component.

Fetching an internal API route from a Server Component is a bad thing anyway. As it is already running on the server, fetch the data from your DB directly. Otherwise, you would most likely get a TypeError: fetch failed during Next.js project build.

Furthermore, Lee Robinson from Vercel explain that in this video called 10 common mistakes with the Next.js App Router.

Sign up to request clarification or add additional context in comments.

2 Comments

Okay that makes sense - thanks. Pulling the api request into the server component works as expected. I was going the api way looking at the NextJS docs here: nextjs.org/docs/app/building-your-application/data-fetching/…. It says to use fetch on the server side to get data. But I didn’t realize this isn’t best practice with internal apis.
Yeah, it isn't for internal APIs. It's my pleasure @LL1997 !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.