How to access .env.local file with Next.js?

Hi there!

For some reasons I can not access the .env.local file in my Next.js application. The documentation from Next js shows a function like this to pass the .env variables:

export async function getServerSideProps() {
   const key = process.env.PUBLIC_API_KEY;
   const secret = process.env.SECRET_API_KEY;

   console.log(`Connecting with API PUBLIC: ${key} and API SECRET ${secret}`);

   return {
     props: {
       hello: 'world',
     },
   };
 }

However, the function I need to have acces to the API keys looks like this:

function process(req, res, detectedIp) {
**SOME CODE**

  const key = key;
  const secret = secret;

**SOME CODE**
}

I am NOT able to acces the .env variable like this:

function process(req, res, detectedIp) {
**SOME CODE**

  const key = key.process.env.PUBLIC_API_KEY;
  const secret = secret.process.env.SECRET_API_KEY;

**SOME CODE**
}

Is it neccessary to use getServerSideProps function to access the .env variables? If so how can I pass the .env variables into another function?

I already tried to fix it for a few hours, but something went wrong and I dont know why.
Can someone please help me with this?

If you need more information, pls let me know.

Thanks for help !!

Why do you have key and secret in front of process.env?

Oh this was a misstake, now it looks like this:

function process(req, res, detectedIp) {
**SOME CODE**

  const key = process.env.PUBLIC_API_KEY;
  const secret = process.env.SECRET_API_KEY;

**SOME CODE**
}

However there is still an error (PUBLIC_API_KEY is undefined):

Btw the spelling is correct, so why I get back undefined?

Edit: I also changd the name to:

const key = process.env.local.PUBLIC_API_KEY;

There is still an error :confused:

Where is the env file located, in the root folder?

Note : If you are using a /src folder, please note that Next.js will load the .env files only from the parent folder and not from the /src folder.

It is located in the root folder (I dont use a src folder)

Thats correct, rght? Always use .env in the root folder.

Edit: Maybe it helps, when I rename the .env file to .env.local then I lose the icon which shows up usually for .env files inside VSCode. However when I start the application the I see in the console that the .env.local file gets loaded.

How is this function used?

If it is a route handler/controller how are you exporting it? I believe it has to be a default export. Did you try just adding export default before function.

Yes I tried to add export default before the function, but then I get this error:

Error:
  x the name `default` is exported multiple times

This is the content of the whole function:

function process(req, res, detectedIp) {
  // req.body contains the JSON data sent by TradingView with sub account, asset, strategy name, action (buy true or false)
  const newTrigger = req.body;
  triggersRepo.create(newTrigger, detectedIp);

  // Get strategy item
  const strategy = strategiesRepo.getByCode(newTrigger.strategy);
  if (!strategy) throw 'Strategy Not Found';

  // Get API key from .env

  const key = process.env.PUBLIC_API_KEY;
  const secret = process.env.SECRET_API_KEY;

  const client = new RestClient(key, secret, {
    subAccountName: newTrigger.subaccount,
  });

  // Get balance from FTX on specific subacount
  (async () => {
    processBalance(newTrigger, strategy, client, await client.getBalances());
  })();

  // TODO : Add LEVERAGE and FUTURES

  return res.status(200).json({ status: 'ok:' });
}

EDIT: I dont see that the function gets exported, is it neccessary to export the function to have access to the .env variables?

EDIT2: I tried to export everything, but still got the same error.

I still have no idea how it is used or where it is used.

api-routes

For an API route to work, you need to export a function as default (a.k.a request handler ), which then receives the following parameters:

If it’s used as a middleware function I believe you have to call it inside the route handler and pass it the req/res.

1 Like

Yes it is used as a middleware function!

Look at the docs and read some of the examples.

Ok, I read the documentation and I tried different export method, but non of them worked. Then I added:

  env: {
    PUBLIC_API_KEY: 'PUBLIC_API_KEY',
  },

to the next.config.js file next.js.config.js Environmental variables then I paste the PUBLIC_API_KEY to const key = { PUBLIC_API_KEY }; and of course I get the error ReferenceError: PUBLIC_API_KEY is not defined

None of this worked, but I think it has something to do with the next.config.js file because I never write something there for the .env variables.

However my head is out of order now, if someone has an idea please let me know.

I will check later again…

Edit: I also tried like this:

  env: {
    PUBLIC_API_KEY: process.env.PUBLIC_API_KEY,
    SECRET_API_KEY: process.env.SECRET_API_KEY,
  },

inside the next.config.js file, but still the same error :confused:

AAAARGHH !!! Finally I found the error :slight_smile:

I called process.env.PUBLIC_API_KEY from a function named process the same name like PROCESS.env.PUBLIC_API_KEY

function process(req, res, detectedIp) {

I renamed the function to process1 like this:

function process1(req, res, detectedIp) {

and then it worked… This was a hard one for me.

@lasjorg Thanks a lot for your help!!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.