Next.js Discord

Discord Forum

Server Side API doesn't work

Unanswered
Giant panda posted this in #help-forum
Open in Discord
Avatar
Giant pandaOP
Hi there

quick question, how I can make my API working?

It works locally, doesn't work once I deploy to vercel.

What I do?

1. Create simply nextjs app - v14.
2. Create /app/api/route.ts with simple response,

// route.ts
import { NextResponse } from "next/server";

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export async function GET() {
const users = await prisma.user.findMany();

return NextResponse.json({ test: users });
}

3. Create a page /app/dashboard/page.tsx

const getData = async () => {
const response = await fetch(${process.env.VERCEL_URL}/api, {
headers: {
Accept: "application/json",
method: "GET",
},
});

return response.json();
};

const Dashbard = async () => {
const apiData = await getData();
return <div>test dashboard data: {JSON.stringify(apiData)}</div>;
};

export default Dashbard;

4.Deploy

Issue that I'm facing, it can't build the app
Failed to parse URL from test-nextjs-8nkjmhtfk-sebastians-projects-ff1ead43.vercel.app/api

if I add https to the process.env.VERCEL_URL so the url will be https://test-nextjs-8nkjmhtfk-sebastians-projects-ff1ead43.vercel.app/api

the issue is:
SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON

Looks like it can't build the app.
I can't call my nextjs API via postman once is deployed to vercel, but it works with localhost

Looks like there is some kind of auth? Postman says 401Unauthorized
And I get a bunch of html, so that makes a sense why I can see "SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON"

Anyway, the question is,
How I can call my own API, on server side in the nextjs, once the nextjs is deployed to vercel?

2 Replies

Avatar
Ray
https://vercel.com/blog/common-mistakes-with-the-next-js-app-router-and-how-to-fix-them#using-route-handlers-with-server-components
you shouldn't fetching route handler in server component. you should move the prisma query to getData instead
Avatar
Giant pandaOP
nice one, thank you, looks like next js 14 works slightly different than older versions 🙂