Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS: dev only pages

I would like to create a /storybook page. But this page is for development purpose only. I mean, I don't want this page to be accessible in production mode.

How can we achieve that?

like image 411
Cequiel Avatar asked Jul 17 '26 02:07

Cequiel


2 Answers

I'm not sure what the best way to do this is. I think you have a couple of approaches.

With Next.js 9.5+

You can use rewrite to make sure traffics to /storybook will go to your 404 page.

// next.config.js
// more configs
  async rewrites() {
    return [
      {
        source: '/storybook',
        destination: process.env.NODE_ENV === 'production' ? '/404' : '/storybook',
      }
    ];
  },
// more configs

With Next.js 10+

You can use the notFound attribute in your getServerSideProps or getStaticProps. For more information, you can find the doc here

// or getServerSideProps
export function getStaticProps() {
  return {
    // returns the default 404 page with a status code of 404 in production
     notFound: process.env.NODE_ENV === 'production'
  }
}

With Custom Server

Depends on the server framework, you can do the redirect to 404 there.

like image 152
Andrew Zheng Avatar answered Jul 18 '26 14:07

Andrew Zheng


My not perfect solution... for Next.js using App Router is by adding a condition in a top layout.tsx file to response with a notFound() when is called outside the development environment.

As example: Create router group /(dev)/ directory with a layout.tsx file and then move /storybook directory inside of it.

/(dev)/layout.tsx

import React from "react";
import {notFound} from "next/navigation";

export default function DevLayout({children}: {
  children: React.ReactNode
}) {
  if (process.env.NODE_ENV != 'development')
    notFound()
  
  return <>{children}</>
}
like image 40
Daniel De León Avatar answered Jul 18 '26 16:07

Daniel De León



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!