Asking
Asking

Reputation: 4192

Access variables in NextJs

I want to use variables in NEXTjs application. For this i did:

  1. created file: .env.local with:

DB_HOST=localhost
DB_USER=myuser
DB_PASS=mypassword

And i want to access this: console.log(process.env.DB_HOST, 'local variables')
When i do this i get undefined. Why it happens, and how to get the variables?

Upvotes: 0

Views: 480

Answers (2)

Ibrahim Abdallah
Ibrahim Abdallah

Reputation: 71

If you are using nextjs higher than 9.4 you can use next.config.js

Snippet from nextjs documentation https://nextjs.org/docs/api-reference/next.config.js/environment-variables

To add environment variables to the JavaScript bundle, open next.config.js and add the env config:

module.exports = {
  env: {
    customKey: 'my-value',
  },
}

Upvotes: 0

enoch
enoch

Reputation: 3123

If you want to access to your environment variables on client side and server side, they must be prefixed with NEXT_PUBLIC

NEXT_PUBLIC_DB_HOST=localhost
NEXT_PUBLIC_DB_USER=myuser
NEXT_PUBLIC_DB_PASS=mypassword

if you are going to use them only on the server side, then your example will work

DB_HOST=localhost
DB_USER=myuser
DB_PASS=mypassword

Upvotes: 1

Related Questions