Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 792
Guilhem Fry Avatar asked Sep 06 '25 19:09

Guilhem Fry


1 Answers

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

like image 53
styfle Avatar answered Sep 09 '25 22:09

styfle