Staging and production cookies in Next.js

Published on 20 November 2019

This article describes how add authentication to your Next.js app using cookies and JWT. In this example, we use cookies to authenticate against a GraphQL Yoga backend. Additionally, we pass parameters based on the deployment stage (local, staging ,or production) of our app.

Deploy stage environmental variable

In this example, we are using Apex Up, which automatically generates an environmental variable UP_STAGE. Depending on your deployment process, you can pass in the stage in a similar way.

We also pass in the following environmental variables:

  • BACKEND_URI_STAGING: The expected domain of the GraphQL backend in staging
  • BACKEND_URI_PROD: The expected domain of the GraphQL backend in prod

In next.config.js in the root directory of your Next application:

// Set up environmental variables for deployment. 
// UP_STAGE comes with UP (
let backendUri = 'http://localhost:4000';
let cookieDomain = 'localhost';
if (process.env.UP_STAGE === 'staging') {
  backendUri = process.env.BACKEND_URI_STAGING;
  // Using a domain like includes all subdomains of
  cookieDomain = '';
} else if (process.env.UP_STAGE === 'production') {
  backendUri = process.env.BACKEND_URI_PROD;
  cookieDomain = '';

if (process.env.UP_STAGE && !backendUri) {
  throw new Error('No backend URI found for : ' + process.env.UP_STAGE);
console.log('Using backend URI: ' + backendUri);

module.exports = withCss({
  // target: 'serverless',
  env: {
    upStage: process.env.UP_STAGE,