Overriding Environment Variables for Local Development
Illustrate how to override production environment variables locally using a .env.local file in a Next.js project.
// .env.local
API_URL=http://localhost:3000/api
Create a .env.local file in the root of your Next.js project with the environment variables you want to override for local development. Here, API_URL is being set to the local development API endpoint.
// next.config.js
module.exports = {
env: {
API_URL: process.env.API_URL,
},
};
In your next.config.js file, add an 'env' property to your module.exports object. Map the API_URL from the process.env to make it available in your Next.js application.
// Usage in your application code
console.log(process.env.API_URL);
In your application, you can now access the overridden API_URL environment variable using process.env.API_URL. The value will be taken from your .env.local file when developing locally, effectively overriding the production environment variable.