Guilhem Fry
Guilhem Fry

Reputation: 326

Environment variable in Vercel redirects

I want to deploy my create-react-app to Vercel.

I define my redirects in my now.json as follows:

{
   "redirects": [
      { "source": "/api/(.*)", "destination": "BACKEND_URL/$1", "statusCode": 200 }
   ]
}

The destination URL depends on the environment variable BACKEND_URL, which is defined in the Vercel dashboard.

I am trying to replace the environment variable in the redirects in the following build command: sed -i "s|BACKEND_URL|${BACKEND_URL}|g" now.json && yarn build

But unfortunately now.json doesn't seem to be available at build time:

09:54:44.243 sed: can't read now.json: No such file or directory

How to enable dynamic redirects in Vercel?

Upvotes: 4

Views: 2528

Answers (2)

Peaceful James
Peaceful James

Reputation: 2235

I think this actually is possible. If you are using create-react-app then you just need to preface your env var name with REACT_APP_. See here: https://create-react-app.dev/docs/adding-custom-environment-variables/

I am currently doing this with a websocket URL env var. I have named it REACT_APP_WS_URL and here is how I use it.

I have 2 different vercel files in the project:

  1. vercel.staging.json which has this section:
  "build": {
    "env": {
      "REACT_APP_WS_URL": "wss:staging.my-backend.com/socket"
    }
  }
  1. vercel.live.json which has this section:
  "build": {
    "env": {
      "REACT_APP_WS_URL": "wss:my-backend.com/socket"
    }
  }

I deploy to them with either of these commands:

vercel deploy --prod -A vercel.staging.json
vercel deploy --prod -A vercel.live.json

and in my code I can access process.env.REACT_APP_WS_URL anywhere.

I have not tried doing this with the Vercel dashboard env vars but it might be worth trying your original approach except rename your env var to REACT_APP_BACKEND_URL.

Note: my deployment commands only work when I don't assign domains to the project. If I assign domains to a project, they are automatically used for ALL --prod deploys, no matter what is in my alias field in the json config file.

Upvotes: 1

styfle
styfle

Reputation: 24610

This is not possible since now.json is read to determine how to build so you can't dynamically generate it during a build.

Instead, consider using a framework like Next.js which provides a next.config.js that can read environment variables as defined in RFC 9081.

npm install next@canary react react-dom
// next.config.js
module.exports = {
  experimental: {
    async redirects() {
      return [{
        source: "/api/:path*",
        destination: `${process.env.BACKEND_URL}/:path*`,
        permanent: false,
      }]
    }
  }
};

https://github.com/zeit/now/discussions/4351

Upvotes: 1

Related Questions