Skip to content

Getting environment variables to work in next js and netlify

I have deployed a next js application to netlify using git and I have a .env.local file that stores the backend route url that I use everywhere throughout the app when making fetch requests. The problem is that after deployment the process.env.NEXT_PUBLIC_BACKEND_ROUTE returns undefined.

The .env.local file:

NEXT_PUBLIC_BACKEND_ROUTE=https://[the name of the url]

An example of a page using the environment varible:

import axios from 'axios';
import { useRouter } from 'next/router';
import { useEffect } from 'react';

export default function Home() {
  const router = useRouter();
  useEffect(() => {
      .then((doc) => {
        const arr =;

        if (arr.length !== 0) {
          const mappedArr = => {
          const amount = mappedArr.length;
          const rand = Math.floor(Math.random() * amount);
          const routeId = mappedArr[rand];
  }, [null]);
  return <div></div>;



There are two possibilities I see

  1. your .env.local file is not in root

  2. Some weird formatting issue is going on with the variables. In that case, try surrounding your variable in quotes:

    NEXT_PUBLIC_BACKEND_ROUTE=”https://[the name of the url]”