{"id":209,"hash":"73c318b18f88844b5d1abff50fef81d2bf848af7bea62d4e99f82fa443f3b1e9","pattern":"How to redirect 404 errors to a page in ExpressJS?","full_message":"I don't know a function for doing this, does anyone know of one?","ecosystem":"npm","package_name":"node.js","package_version":null,"solution":"I found this example quite helpful:\n\nhttps://github.com/visionmedia/express/blob/master/examples/error-pages/index.js\n\nSo, it is actually this part:\n\n// \"app.router\" positions our routes\n// above the middleware defined below,\n// this means that Express will attempt\n// to match & call routes _before_ continuing\n// on, at which point we assume it's a 404 because\n// no route has handled the request.\n\napp.use(app.router);\n\n// Since this is the last non-error-handling\n// middleware use()d, we assume 404, as nothing else\n// responded.\n\n// $ curl http://localhost:3000/notfound\n// $ curl http://localhost:3000/notfound -H \"Accept: application/json\"\n// $ curl http://localhost:3000/notfound -H \"Accept: text/plain\"\n\napp.use(function(req, res, next) {\n  res.status(404);\n\n  // respond with html page\n  if (req.accepts('html')) {\n    res.render('404', { url: req.url });\n    return;\n  }\n\n  // respond with json\n  if (req.accepts('json')) {\n    res.json({ error: 'Not found' });\n    return;\n  }\n\n  // default to plain-text. send()\n  res.type('txt').send('Not found');\n});","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/6528876/how-to-redirect-404-errors-to-a-page-in-expressjs","votes":283,"created_at":"2026-04-19T04:41:32.692697+00:00","updated_at":"2026-04-19T04:51:14.645921+00:00"}