简体   繁体   中英

NextJS not reading environment variables

I have a NextJS app which is running Next.js v12.2.5, but it doesn't seem to be reading environment variables.

I have created a .env.local file which has:

NEXT_PUBLIC_SERVER_URL=http://localhost:3001

And my next.config.js is:

/** @type {import('next').NextConfig} */
const withTM = require('next-transpile-modules')(['react-daisyui'])
module.exports = withTM({
    reactStrictMode: true,
    swcMinify: true,
    images: {
        domains: ['placeimg.com'],
    },
    env: {
        NEXT_PUBLIC_SERVER_URL: process.env.NEXT_PUBLIC_SERVER_URL,
    },
})

In one of my component's index.tsx file, I'm doing the following:

const apiURL = process.env.NEXT_PUBLIC_SERVER_URL

console.log(process.env.NEXT_PUBLIC_SERVER_URL)
console.log(apiURL)

On the server once I do npm run dev and go to the route on Chrome, I get the following for my log statements:

undefined
undefined

And on the browser I get:

trips:1          GET http://localhost:3000/trips 404 (Not Found)

Note my NextJS is on http://localhost:3000 and my Express backend which I'm trying to connect to is on http://localhost:3001

Why is NextJS not reading the environment variables I have set?

You can try, dotenv. remember to install the package 'npm i dotenv --save'

Then create a.env file on your src folder and type down the info like

db=POSTGRES

id=ALAN

password=fjord

Once you do this, you'll be able to have access to the info by doing something like

const id = process.env.id

BY THE WAY.. Importing dotenv to the file you're using is not done import * from 'dotenv' < This is bad

Should be imported like this require('dotenv').config()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM