I’m trying to fetch user data from mongoDb in my NextJs project (app router) using api route handlers. It works perfectly fine locally, builds locally and on Vercel without issues.
The register and login functionality has been working flawlessly as well (nextAuth credentials). So POST requests to mongo isn’t an issue.
It’s specifically after I added my fetch to GET user data after login that I get this issue on Vercel only.
Got env’s “BASE_API_URL” (with and without next_public), MONGODB_URI, NEXTAUTH_SECRET NEXTAUTH_URL.
Deploy logs say:
Request: OPTIONS /
Message: “SyntaxError: Unexpected token ‘<‘, “<!doctype “… is not valid JSON… …at async M (/var/task/.next/server/chunks/333.js:1:6961) {
digest: ‘981736902’
}”
as well as “[OPTIONS] / status=500”
And
Request: GET /
Same message
My fetch (atm a server component):
const session = await getServerSession(options);
const userId = session?.user?.id;
const res = await fetch(
`${process.env.NEXT_PUBLIC_API_BASE_URL}/api/user/${userId}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
},
}
);
const user = await res.json();
Api route /api/user:
export async function GET(
req: NextRequest,
{ params }: { params: { id: string } }
) {
const userId = params.id;
try {
await dbConnect();
const user = await User.findById(userId);
if (!user) {
return NextResponse.json({ error: "Can't find user" });
}
return NextResponse.json({ user: user }, { status: 200 });
} catch (err: any) {
return NextResponse.json({ error: err.message }, { status: 500 });
}
}
Fairly new to coding and this is my first Vercel deployment and nextjs project ever, I really can’t figure out what I’m doing wrong.
I’ve tried adding CORS headers in my next.config file with no luck.
Thank you 🙂
Rebecca Fischer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.