Shikshit
Shikshit

Reputation: 63

AWS Amplify environment variables not working for NextJS app

I recently deployed my next application on AWS Amplify and learned that Amplify cannot access my environmental variables. However, if I use the .env file in my root directory for production, it works, but Amplify environmental variables are not working. I have tried changing build settings as per AWS amplify documentation. Kindly help.

Build Settings

version: 1
frontend:
  phases:
    preBuild:
      commands:
        - npm ci
    build:
      commands:
        - env | grep -e MONGODB_URI >> .env.production
        - env | grep -e NEXT_PUBLIC_ >> .env.production
        - npm run build
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*
      - .next/cache/**/*

And please let me know about this line if it can help "To modify your app's build spec choose 'Edit'. Alternatively, you may download the YML file and deploy in the root of your repository to amplify.yml to override this setting."

How can i use yml file in my root directory to resolve this issue once and for all

enter image description here

Upvotes: 2

Views: 682

Answers (1)

kimchi
kimchi

Reputation: 3

adding echo env solved it for me for your case example

version: 1
frontend:
  phases:
    preBuild:
      commands:
        - npm ci
    build:
      commands:
        - echo "EMAIL=$EMAIL" >> .env
        - echo "EMAIL_PASS=$EMAIL_PASS" >> .env
        - npm run build
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*
      - .next/cache/**/*
and you can add another line (- echo ...) for all your env,

after change amplify.yml you can restart/redeploy again

you also can see the docs from AWS, ADDING ENV DURING BUILD TIME AMPLIFY

Upvotes: 0

Related Questions