How to fix a NextJS hydration error when determining baseURL for APIs

40 Views Asked by At

I am trying to set up tRPC for a project, and they have the below function to determine the necessary URL root depending on where an API is called. This comes straight from this tRPC doc: https://trpc.io/docs/client/nextjs/setup (go to step 4 - Create tRPC Hooks)

function getBaseUrl() {
  if (typeof window !== 'undefined')
    // browser should use relative path
    return '';
  if (process.env.VERCEL_URL)
    // reference for vercel.com
    return `https://${process.env.VERCEL_URL}`;
  if (process.env.RENDER_INTERNAL_HOSTNAME)
    // reference for render.com
    return `http://${process.env.RENDER_INTERNAL_HOSTNAME}:${process.env.PORT}`;
  // assume localhost
  return `http://localhost:${process.env.PORT ?? 3000}`;
}

I understand this is a commonly-used check, but it's also causing a NextJS hydration error when I run locally (I checked by commenting out this code and it resolves).

I've read this doc: https://nextjs.org/docs/messages/react-hydration-error. But it doesn't make sense to me to rewrite every instance of this function (at least in client components) to use useEffect, for example, as suggested on the docs. It seems that the whole point of the function is to avoid having to do this.

Is there a workaround, or is this generally just suppressed somehow in this special case?

0

There are 0 best solutions below