#how to display different data based on vercel env
1 messages · Page 1 of 1 (latest)
You can display different data based on the environment by using environment variables and conditional logic in your scripts. Here's a step-by-step guide on how to do it:
- Set up your scripts in
package.json: You can specify different scripts to be run for your preview and production environments. For example:
{
"scripts": {
"build:production": "next build",
"build:preview": "echo \"Let's build a preview!\" && next build"
}
}
Source (https://vercel.com/guides/dynamic-build-commands)
- Create a
vercel.shfile: This file will contain conditional logic to run a script according to the environment. You can use theVERCEL_ENVenvironment variable to determine the current environment:
#!/bin/bash
if [[ $VERCEL_ENV == "production" ]] ; then
npm run build:production
else
npm run build:preview
fi
Source (https://vercel.com/guides/dynamic-build-commands)
- Set your Build Command to use
vercel.sh: You can do this either in yourvercel.jsonfile or in the project dashboard:
- Using a
vercel.jsonfile:
{
"buildCommand": "sh vercel.sh"
}
Source (https://vercel.com/guides/dynamic-build-commands)
- Using the project dashboard: Select your project from the dashboard and go to the Settings tab. Under Build & Development Settings, set the value of the Build Command to be
sh vercel.sh.
- Accessing Environment Variables: Inside your application, you can access environment variables through
process.env.YOUR_VALUE. For example:
import fetch from 'node-fetch';
export default async function handler(request, response) {
const res = await fetch('<https://...',> {
method: 'POST',
body: JSON.stringify({
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
}),
headers: { 'Content-Type': 'application/json' },
});
const data = await res.json();
return response.status(200).json({ data });
}
Source (https://vercel.com/guides/how-to-add-vercel-environment-variables)