1

I am working on a Next.js project (Prisma as ORM) that contains multiple parts where dynamic pages are created often.

Until now, I fetched the data using getStaticProps and getStaticPaths. I realized only now that these are only run at build time and my project only works in development for the moment.

I tried to change the data fetching to useSWR with a fetcher:

...
const fetcher = (...args) => fetch(...args).then((res) => res.json());

export default function View() {
    const { data, isLoading, error } = useSWR('/api/survey-data', fetcher);
    const survey = data?.survey;

    if(error) return <div>Failed to load</div>;
    if(isLoading) return <Loading/>;
...

Passing through an api that calls a function that gets the data from the database using Prisma, which causes this error:

Unhandled Runtime Error Error: PrismaClient is unable to be run in the browser

I am unable to find a concrete example on what is the best practice for my use case. How can I fetch my data when Prisma can't run on the client?

Thank you for any insight!

1 Answer 1

0

You could stick with getStaticProps and use Incremental Static Regeneration, but if your data is changing that much, you could use getServerSideProps, as an example:

// pages/posts/[slug].js

export default function Post({ post }) {
  return <div>{post.title}</div>;
}

export async function getServerSideProps(context) {
  const post = await prisma.post.findUnique({
    where: {
      id: context.query.slug,
    },
  });
  if (!post) {
    return {
      notFound: true,
    };
  }
  return { props: { post } };
}

getServerSideProps runs on the server, so you will no longer get that Prisma error, and also, because it runs at request time, your user will get the most up-to-date data.

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

1 Comment

That is a way better solution, it solved it thank you !

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.