Next.js Discord

Discord Forum

[NextJS13] GraphQLClient url undefined when called inside client component

Answered
PepeW posted this in #help-forum
Open in Discord
I'm working on a NextJS13 project.
I'm using the version graphql-request ^6.1.0.

I've set up my GraphQLClient like this:
// file: graphqlClient.ts
import { GraphQLClient } from "graphql-request"
export const graphqlClient = new GraphQLClient(process.env.NEXT_INTERNAL_GRAPHQL_URL as string)


Inside a RSC, when I console.log(graphqlClient), I can see that the url is being defined:
import { graphqlClient } from "@/utils/lib/graphql/graphqlClient"

export default async function SignupPage() {
  console.log(graphqlClient)
  /* GraphQLClient {
    url: 'http://host.docker.internal:14000/graphql',
    ...
  } */
}


But when I'm inside a client component the url inside graphqlClient is undefined:
"use client"

import { graphqlClient } from "@/utils/lib/graphql/graphqlClient"

export default async function SignupForm() {
  console.log(graphqlClient)
  /* GraphQLClient {
    url: undefined,
    ...
  } */
}


Am I missing something or is it a bug ?
Answered by Rafael Almeida
client components run both in the server and the client, so you need to expose this env variable to the browser as well. you can do that by adding the NEXT_PUBLIC_ prefix to the variable name. see: https://nextjs.org/docs/app/building-your-application/configuring/environment-variables#bundling-environment-variables-for-the-browser
View full answer

2 Replies

client components run both in the server and the client, so you need to expose this env variable to the browser as well. you can do that by adding the NEXT_PUBLIC_ prefix to the variable name. see: https://nextjs.org/docs/app/building-your-application/configuring/environment-variables#bundling-environment-variables-for-the-browser
Answer
You're correct, I feel dumb, thank's