Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here are the steps to set up custom error pages for 404 and 500 errors on your Next.js application:

  1. Create the pages for the custom error pages:
    • For 404 errors, create a file called 404.js in the pages directory.
    • For 500 errors, create a file called 500.js in the pages directory.
  2. In each file, add the following code:

    function CustomErrorPage() {
     return (
       <div>
         {/* Add your custom error message and styles here */}
       </div>
     )
    }
    
    export default CustomErrorPage
    
  3. In your Next.js configuration file (usually next.config.js), add the following code:

    module.exports = {
     // ...
     webpack: (config, { isServer }) => {
       if (isServer) {
         require('./scripts/generate-sitemap') // Your custom sitemap file
         const originalEntry = config.entry.bind(config)
         config.entry = () => originalEntry().then(entry => {
           entry['./scripts/generate-sitemap'] = './scripts/generate-sitemap.js'
           return entry
         })
       }
    
       return config
     },
     // ...
     eslint: {
       ignoreDuringBuilds: true,
     },
     serverRuntimeConfig: {
       // Will only be available on the server side
       mySecret: 'secretsauce',
       SECOND_SECRET: process.env.SECOND_SECRET, // Pass through env variables
     },
     publicRuntimeConfig: {
       // Will be available on both server and client
       staticFolder: '/public',
     },
     distDir: 'build',
     webpackDevMiddleware: (config) => {
       return config;
     },
    }
    
  4. Add the following code to your next.config.js file so that Next.js knows to use the custom error pages:

    module.exports = {
     // ...
     exportTrailingSlash: true,
     async rewrites() {
       return [
         {
           source: '/404',
           destination: '/404',
         },
         {
           source: '/500',
           destination: '/500',
         },
       ]
     },
     async redirects() {
       return [
         {
           source: '/404',
           destination: '/404',
           permanent: true, // true means a 301 redirect
         },
         {
           source: '/500',
           destination: '/500',
           permanent: true,
         },
       ]
     },
     // ...
    }
    
  5. Restart your server to see the changes take effect.

That's it! Now your Next.js application will show custom error pages for 404 and 500 errors.