Hiding API Secrets with Server-Only Environment Variables

Showcase how to use environment variables in Next.js that should remain server-only and never be exposed to the client-side.
// server.js 
import express from 'express';
import dotenv from 'dotenv';


const app = express();

// An endpoint that uses the secret API key
app.get('/api/data', function(req, res) {
  // Access the API_SECRET from the environment variables
  const apiSecret = process.env.API_SECRET;
  // Use the secret to get data from an API
  // ... fetch data using the secret ...
  // Send data back to the client
  res.json({ data: 'fetched data' });

app.listen(3000, () => console.log('Server running on port 3000'));
This server-side code uses the dotenv package to load environment variables and creates an endpoint that uses a server-only API secret without exposing it to the client.
// next.config.js
module.exports = {
  env: {
    // This will be available on both server and client
  serverRuntimeConfig: {
    // Will only be available on the server side
    API_SECRET: process.env.API_SECRET, // Passed from env variable
  publicRuntimeConfig: {
    // Will be available on both server and client
    staticFolder: '/static',
This Next.js configuration demonstrates how to define environment variables in 'next.config.js'. It shows separation between public configuration accessible by the client and server-only runtime configuration.
// pages/api/sensitive.js
import getConfig from 'next/config';

export default async (req, res) => {
  const { serverRuntimeConfig } = getConfig();
  const apiSecret = serverRuntimeConfig.API_SECRET;

  // Perform server-side operations using apiSecret
  // e.g., Fetch data from an API, etc.

  res.status(200).json({ success: true });
This is an example of a Next.js API route where the server-only environment variable is used securely. It uses 'getConfig' from 'next/config' to access 'serverRuntimeConfig' which contains the server-only secret.