How to set up dev/staging-only pages in NextJS

Published on

Recently I had to create a new version of landing page. During development, it must be available only in development and staging environments. Once finished - it must be enabled in prod.

There are many ways how to approach this. The most basic one is checking the current environment directly in the component. If this is production - simply don't return any content.

import { notFound } from 'next/navigation'

const Page = () => {
	const isProduction = process.env.VERCEL_ENV === 'production'
	if (isProduction) {
		return notFound()
	}

	return <div>page content</div>
}

This works but has a number of obvious downsides:

  • You can't know what page is supposed to be disabled in production unless you open a file and read it carefully
  • You can easily forget to remove it for the very same reason

A much better option is to take advantage of the Next.js config. It allows us to specify the page extensions that the framework looks for. By default, these are .tsx, .ts, .jsx, .js.

We will need to add one more - specifically for non-prod pages - .dev.tsx. We will include it in NextJS config only for non-production environments.

Our next.config.js should now look like this:

import type { NextConfig } from 'next'

const isProduction = process.env.VERCEL_ENV === 'production'
const prodExts = ['ts', 'tsx', 'js', 'jsx']
const devExts = ['dev.tsx']

const pageExtensions = isProduction ? prodExts : [...prodExts, ...devExts]

const nextConfig: NextConfig = {
  pageExtensions,
}

export default nextConfig

Now when we want to create a page that is available only in non-prod environments - all we have to do is name it Page.dev.tsx.

Once deployed, in non-prod environments it will work just like any other page, but in prod - you won't be able to see it.

When you are ready to make it publicly available - all you have to do is change its extension from .dev.tsx to .tsx.

This solution allows us to:

  • Instantly see which pages are not intended for prod without reading the code
  • Easily move them to prod without making changes to the code