Here are the steps to set up custom error pages for 404 and 500 errors on your Next.js application:
404.js
in the pages
directory.500.js
in the pages
directory.In each file, add the following code:
function CustomErrorPage() {
return (
<div>
{/* Add your custom error message and styles here */}
</div>
)
}
export default CustomErrorPage
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;
},
}
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,
},
]
},
// ...
}
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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-10-03 11:00:00 +0000
Seen: 11 times
Last updated: Jan 18 '22
Is it possible to globally install System.Data.OleDb?
How to debug NextJS application in VSCode?
Why does the app shut down when switching to the Google Maps section in a Flutter application?
How can an application Manager be put in place to manage the system?
How can a Qt application detect a trigger triggered by a batch script?
How can I execute a React Native application on my Android device?
What conditions could cause Wildfly to automatically undeploy an EAR?
How can an application be run with parameters from the context menu?