Cannot read environment variables in Nuxt app

Hello,

Here is my site:
https://elastic-chandrasekhar-ca7631.netlify.app/login/

I’m doing a little clone for school and I’m not able to authenticate against my Laravel endpoint (AWS). It appears that the issue is that my CLIENT_ID and CLIENT_SECRET registered with Laravel (passport) are coming back NULL. I have defined them in the Netlify UI Environment Variables section.
Here is the code authenticating the user:

    async passwordGrantLogin() {
  try {
    await this.$auth.loginWith('password_grant', {
      data: {
        grant_type: 'password',
        client_id: process.env.PASSPORT_PASSWORD_GRANT_ID,
        client_secret: process.env.PASSPORT_PASSWORD_GRANT_SECRET,
        scope: '',
        username: this.user.username,
        password: this.user.password
      }
    })

Interestingly, it’s posting correctly to LARAVEL_ENDPOINT which the $auth module is configured to use in nuxt.config.js, but the CLIENT_ID and CLIENT_SECRET are not being read. The actual XHR going through looks like this:

{“grant_type":“password”,“scope”:“”,“username”:"jack@example.com”,“password”:“password”}

Locally, it looks like this:

{“grant_type”: “password”,“client_id”: “1”,“client_secret”: “BTvUzKBA62ewVS4dT30hJ2eS2TUwSlY0bweTaI0h”,“scope”: null,“username”: “jack@example.com”,“password”: “********”}

Also, registering a user works fine. It’s just attempting to read these two variables that causes the issue. I have not figured out why yet. Thank you.

EDIT: I see that process.env.LARAVEL_ENDPOINT is defined as the baseURL for axios in nuxt.config.js, which I am guessing is interpolated at build time. I read carefully the post about using environment variables correctly in netfliy, and I think the issue may be that process.env.CLIENT_ID and CLIENT_SECRET are not read until browse time when the login attempt is made… obviously not being there.

I am pretty new to software development, so I apologize if this question is a pain. But how can I get my client_id and client_secret over to this component? Does this require a serverless function?

I’ve created a script to extract the environment variables into a .env file at build time. I hope this is alright. It works like a charm.

Hi, @bacchus, if it works for you, doing so does not break any rules and I’m glad you found a solution. If you want to, please feel free to post your code here (minus any private details of course) to share it with the community.

You don’t have to do so but, if you did, I’m sure others searching here for a similar solution would appreciate it. :wink:

Sure, of course. Here’s the script:

const fs = require('fs')

fs.writeFileSync(
‘./.env’,
LARAVEL_ENDPOINT=${process.env.LARAVEL_ENDPOINT}\n PASSPORT_PASSWORD_GRANT_ID=${process.env.PASSPORT_PASSWORD_GRANT_ID}\n PASSPORT_PASSWORD_GRANT_SECRET=${process.env.PASSPORT_PASSWORD_GRANT_SECRET}\n
)

Here’s the npm script I call from Netlify

“build”: “node ./scripts/create-env.js && nuxt build”,