Adding Environment Variables

Provide an example of how to add environment variables in a Next.js application using a .env.local file and accessing them via process.env.
// Create a .env.local file at the root of your Next.js project
Defines environment variables in a .env.local file, which is used to store local environment variables securely
// next.config.js
module.exports = {
  env: {
    customKey: 'my-value',
In next.config.js, you can add additional environment variables which will be replaced during the build step
const apiUrl = process.env.NEXT_PUBLIC_API_URL;
console.log(`The API URL is: ${apiUrl}`);
Accesses the NEXT_PUBLIC_API_URL environment variable from the .env.local file within the Next.js application using process.env
const secretKey = process.env.SECRET_API_KEY;
// Remember: Only use secret keys in server-side code (like getServerSideProps)
// and never expose them to the client side
Accesses the SECRET_API_KEY environment variable within the server-side Next.js code, keeping it secure from the client-side