1

I'm trying to use an environment variable in my serverMiddleware in Nuxt.js. It works fine when it starts with a letter (MY_SECRET) but since it's a private server variable I'd like it to start with an underscore (_MY_SECRET). However for some reason the latter is undefined.

This is my basic setup:

// .env

MY_SECRET = hello
_MY_SECRET = world
// serverMiddleware/index.js

console.log(process.env.MY_SECRET, process.env._MY_SECRET) // output: hello undefined

Why does this happen and what other options do I have to prefix my private variables?

kissu
  • 40,416
  • 14
  • 65
  • 133
DaDo
  • 443
  • 1
  • 6
  • 20

1 Answers1

1

Nvm, you cannot use runtimeConfig in a serverMiddleware (probably because it is out of the Nuxt context) as shown here: https://github.com/nuxt/nuxt.js/issues/2033#issuecomment-773181809

I tried it myself with an underscore and it's working great with a publicRuntimeConfig.


After some research aka this answer and reading the official spec, on top of some Wikipedia, it looks like _ is a valid character for an env. Meanwhile, it is also used as a separator.

I've tried several things, found out that if you prefix it with a _, you won't even have it in process.env, this is not a dotenv issue neither (checked this one too), so I just guess that this is not possible.

Solution

Use PRIVATE_MY_SECRET and you should be good!

kissu
  • 40,416
  • 14
  • 65
  • 133
  • I don't think runtimeConfig works in serverMiddleware? In your answer you said to use process.env.PRIVATE_TOKEN directly. – DaDo Sep 01 '21 at 13:14
  • `serverMiddleware` is on the server so it should totally work. And in my answer, I'm saying to use the new method. `serverMiddleware` is not a module or alike in the `nuxt.config.js`, so feel free to use the `runtimeConfig` approach @DaDo – kissu Sep 01 '21 at 13:16
  • But how do I access a runtimeConfig variable inside serverMiddleware? In a Vue component I access it via this.$config.privateToken but I do not have this context in a server.js file for example. – DaDo Sep 01 '21 at 13:20
  • @DaDo oh yeah, it can also be written directly in the `nuxt.config.js` file as shown here: https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-servermiddleware#usage What if you export it to some external file as shown here? https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-servermiddleware#custom-server-middleware – kissu Sep 01 '21 at 13:22
  • I don't find anything about runtimeConfig or env vars on that page. Just to be clear I already have a fully functional Express API running in my serverMiddleware and I can access variables from my .env file, just not those which start with an `_` character. Those are undefined. – DaDo Sep 01 '21 at 13:28