Next.js Discord

Discord Forum

Problem with deploying to Vercel and .env variables inside project.

Unanswered
DennisK posted this in #help-forum
Open in Discord
Hi!

I need to use some .env variables, but after reading the docs it is still not working. The behaviour is super weird. In my project I have:

A .env file inside the project and repo with just the baseURL. This is working
A .env.local with a project specific API token. This is returning undefined.

In vercel we also added this API token and we are trying to use this like: process.env.API_TOKEN but it does read undefined.

How is this possible and how do we make this work?

export async function fetchVacancies(): Promise<Vacancy[] | string> {
  const apiUrl = `xxxxxx`;

  console.log(process.env.API_KEY); // Undefined
  console.log(process.env.BASE_URL); // Accessable, is within a .env file inside the project.

  const payload: Payload = {
    subdomain: process.env.NEXT_PUBLIC_SUBDOMAIN, // Gives undefined. Added to Vercel
    show: [
      "id",
      "uuid",
      "wp.uuid",
      "wp.published",
      "wp.title",
      "wp.slug",
      "jobTitle",
      "salaryMin",
      "salaryMax",
      "location",
      "contractType",
    ],
    page: 1,
    amount: 12,
    filters: [],
    sort: [],
  };

  const options: Options = {
    params: payload,
    headers: {
      Authorization: `Bearer {process.env.API_TOKEN}`, // Gives undefined. Added to Vercel
    },
  };

  try {
    const response: AxiosResponse = await axios.get(apiUrl, options);

    return response.data as Vacancy[];
  } catch (e: unknown) {
    if (axios.isAxiosError(e)) {
      const errorResponse = e as AxiosError<ErrorResponse>;
      return errorResponse.response?.data.error || "An error occurred";
    }
    return "An unexpected error occurred";
  }
}

11 Replies

Have you checked if the variables are available to your production environment?
Yes. They are defined
I have this weird feeling that it will work if I delete my .env inside my project
I think I found it. We create those variables using the Vercel API
Never mind. Removed them, added them manually and still it is not getting picked up by Next.js. This is super super weird. I am trying to access them in a simple api.ts file inside my lib folder
If the variable is named NEXT_PUBLIC_API_KEY then you need to reference it by its full name like this: process.env.NEXT_PUBLIC_API_KEY.

Keep in mind that it's not advisable to expose api keys to the client.
Prefixing any environment variable with NEXT_PUBLIC_ automatically makes it available to the client and so it is vulnerable to attacks.
That is what I am doing. The key names are a bit weird in my example file above, it is that I was just copying/pasting a piece of code where I was debugging and trying different keys/names. But there is no way we get the env keys working with Vercel. Its crazy
Try exporting all your variables from a single file and using a helper function to assert their value and throw an error if they're not defined.

export function assertValue<T>(v: T | undefined, errorMessage: string): T {
   if (v === undefined) {
      throw new Error(errorMessage);
   }

   return v;
}

export const WEBSITE_URL = assertValue(
   process.env.NEXT_PUBLIC_WEBSITE_URL,
   "Missing environment variable: NEXT_PUBLIC_WEBSITE_URL"
);


It's really weird that you can't access them even after setting them up correctly in Vercel.
Jumbo flying squid
Have you tried logging it? just console.log(process.env)
To see whats inside