Next.js Discord

Discord Forum

Next js api in build does malfunction

Answered
Transvaal lion posted this in #help-forum
Open in Discord
Transvaal lionOP
I am a beginner. I developed an application using Next.js App Router, Next.js API, NextAuth, Prisma, PostgreSQL, and TypeScript. After running the build in Next.js, it was successful. I then started the build and checked the subject upload page, where the subject was successfully uploaded to the database. My application also includes a Library Page that displays all the subjects stored in the database. In development, the page works fine, but in the build, the API returns an empty response to the page. If I upload something in development, create a build, and then run the build, the data tends to show up. However, when I delete the data in the database, the page in the build still displays the data, and the API continues to serve the deleted data.
Answered by iyxan23
heya that's most likely related to the cache
View full answer

54 Replies

Answer
if i would assume, you seem to be calling the database on a react server component. in that case, nextjs will automatically determine that the page is a "static page", where essentially, nextjs will execute the react server components during the build process, fetching some data from your database.
when it is served, the website is static, it does not change at all. this is because the site's html/css/js are already built statically.
to make the site dynamic, you could export a dynamic route segment option as such:
export const dynamic = "force-dynamic";

export default function MyPage() {
  // ... your code
}
it's a bit confusing at first, i was so baffled when i found out about this for the first time 😅
Transvaal lionOP
hey first of all thanks for taking time explain this to me i appreciate it.
what i am actually doing is making an api call to next api route and the route uses prisma to to fetch the data
humm so you're doing a fetch call to itself?
Transvaal lionOP
yes yes
Transvaal lionOP
useEffect(() => {
    async function fetchSubjects() {
      try {
        const response = await fetch('/api/subjects', { cache: 'no-cache' });
        if (response.ok) {
          const data = await response.json();
          console.log(data);
          setSubjects(data);
        } else {
          console.error('Failed to fetch subjects');
        }
      } catch (error) {
        console.error('Error fetching subjects:', error);
      } finally {
        setLoading(false);
      }
    }
    fetchSubjects();
  }, []);
oh so it's doing it on useEffect, that should work
Transvaal lionOP
import { NextResponse } from 'next/server'; import { prisma } from '../../lib/prisma'; export async function GET() { try { await prisma.$connect(); const subjects = await prisma.subject.findMany(); console.log('Subjects fetched:', subjects); // Debug log to check what's being fetched return NextResponse.json(subjects, { headers: { 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate', 'Pragma': 'no-cache', 'Expires': '0', 'Surrogate-Control': 'no-store', }, }); } catch (error) { console.error('Error fetching subjects:', error); return NextResponse.json({ error: 'Failed to fetch subjects', details: error }, { status: 500 }); } finally { await prisma.$disconnect(); } }
this is my api/subjects
i did a lot of chat gpt so i am not sure about the cache and stuff
ok wow you really did a lot of cache disabling stuff
Transvaal lionOP
chat gpt did it 😅
just to try, could you add the export const dynamic = 'force-dynamic' on your /api/subjects?
i dont think it'd work, but who knows lol
Transvaal lionOP
alright will try it
also, the file is a route.ts file right?
Transvaal lionOP
yes yes
it is
i will try and let you know
Transvaal lionOP
hey it got fixed
it works perfectly fine
oh really? with the dynamic export?
Transvaal lionOP
yes
i wasn't expecting that :lolsob:
Transvaal lionOP
i thought it was only for front end
dayum bro
same to me
idrk what happened there, i never used the dynamic export on my route.ts files
they seem to just work fine without the export
tho im a bit suspicious about the prisma.$connect() call on the function
Transvaal lionOP
even i dont know what it is i didnt even read it fwhen i used chat gpt i was desperate about the outcome
oh okay
i tend to use a simple prisma.ts as such:
import { PrismaClient } from "@prisma/client";

const prismaClientSingleton = () => {
  return new PrismaClient();
};

type PrismaClientSingleton = ReturnType<typeof prismaClientSingleton>;

const globalForPrisma = globalThis as unknown as {
  prisma: PrismaClientSingleton | undefined;
};

const prisma = globalForPrisma.prisma ?? prismaClientSingleton();

export default prisma;

if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;

when referincing prisma, i just use it right away as:
await prisma.subject.findMany({ ... })

no need of any connect or disconnects
perhaps you could try that?
Transvaal lionOP
sure i will give it a try i will have to revert all the unnecessary changes i did. thanks a lot
i am new to this community
👍 good luck with that
@Transvaal lion i am new to this community
its alright, im actually new too; had been contributing only for a few days now, they've been really welcoming as well!
Transvaal lionOP
thats great. you were such a saviour
alright i gotta go
see you around
oh right, it's a tradition here to mark answers as solution, please do
Transvaal lionOP
got it
👍
good luck with next
Transvaal lionOP
you too.