Using Environment Variables in API Routes

Show how to use environment variables within Next.js API routes to configure endpoints with sensitive keys.
// To use this environment variable, add it to your `.env.local` file:
// API_SECRET_KEY=your_secret_key

export default function handler(req, res) {
  // Accessing the environment variable
  const apiSecretKey = process.env.API_SECRET_KEY;

  if (!apiSecretKey) {
    // Handle the error when the API_SECRET_KEY is not set
    return res.status(500).json({ error: 'API_SECRET_KEY is not defined.' });

  // Perform operations using the secret key...
  // For instance, authenticate a request
  if (req.headers.authorization !== apiSecretKey) {
    // Authorization failed
    return res.status(401).json({ error: 'Unauthorized' });

  // Continue to handle the request
  res.status(200).json({ message: 'Success' });
In this piece of code, an API route is defined in Next.js where the environment variable API_SECRET_KEY is used to authenticate API requests. The key is obtained from the environment using 'process.env.API_SECRET_KEY'. The code first checks if the key is set; if it's not, it returns a 500 error. If the key is defined, it compares the 'authorization' header in the incoming request to the secret key. If the keys don't match, it responds with a 401 error for unauthorized access. If the keys match, it processes the request and sends back a success response.