Cristobal
Cristobal

Reputation: 13

Unable to Access Environment Variables in Next.js API Routes

I'm working on a project using Next.js 13 and API routes to interact with a database. I'm trying to store my database credentials in a .env file, but the variables are not being loaded.

I have verified that the .env file is being loaded, but when I log process.env, the output does not include the variables I have defined.

Is there something I am missing or doing wrong? How can I access the environment variables in my Next.js API routes? Any help would be greatly appreciated.

I've attempted to access the variables in the API route index.js using the following code:

export default function handler(req, res) {
  console.log(process.env.DB_NAME);
  console.log(process.env.NEXT_PUBLIC_API_URL);
  console.log(process.env);
  res.status(200).send("OK");
}

Additionally, I have tried using serverRuntimeConfig in next.config.js as shown below:

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  webpack: (config) => {
    config.experiments = { ...config.experiments, topLevelAwait: true };
    return config;
  },
  serverRuntimeConfig: {
    DB_HOST: process.env.DB_HOST,
  },
};

module.exports = nextConfig;

And in my API route index.js:

import getConfig from "next/config";
const { serverRuntimeConfig } = getConfig();
export default function handler(req, res) {
  console.log(serverRuntimeConfig.DB_HOST);
  res.status(200).send("OK");
}

However, the output is always undefined for the variables.

I also tried using getServerSideProps in a page route, but i got the same answer.

I have verified that the .env file is in the root directory of my project. I have also restarted the development server after making changes.

The expected output would'd be 'localhost'

my .env.local file:

DB_NAME: name
DB_USER: postgres
DB_PASSWORD: *****
DB_HOST: localhost
BD_DIALECT: postgres

Upvotes: 1

Views: 6626

Answers (1)

LongLegJim
LongLegJim

Reputation: 305

The variables aren't defined correctly in your .env.local file.

Make sure the variables are defined with an = sign, without a space on either side of it:

.env.local

DB_NAME=name
DB_USER=postgres
DB_PASSWORD=*****
DB_HOST=localhost
BD_DIALECT=postgres

Also note .env.local will only be used when running npm run dev, it will not be used for npm run build or npm run start unless the NODE_ENV variable is explicity set to development.

Because of that I reccommend changing your .env.local file to .env to remove the possibility of NODE_ENV from affecting the initialization of your environment variables.

Upvotes: 2

Related Questions