How to check if a page exist in a custom server using Next.js How to check if a page exist in a custom server using Next.js express express

How to check if a page exist in a custom server using Next.js


I finally solved with:

const glob = require('glob')const path = require('path')// ...const pagesDir = path.resolve(`${__dirname}/../src/pages`)const pages = glob.sync(`${pagesDir}/**/*.js`)  .map(p => p    .replace(pagesDir, '')    .replace('index.js', '')    .replace('.js', '')  )// ...server.get('*',(req, res) => {  const { url, fixed } = fixUrl(req)  if (fixed && pages.includes(url.split('?')[0])) {    res.redirect(301, url)    return  }  handle(req, res)})

If somebody knows a more elegant solution it will be welcome.


This terrible hack doesn't strictly tell you whether a route exists before calling handle, but it does let you hook in and apply your own custom handling of 404 errors before next renders anything to the res.

const errorRenderer = app.server.renderErrorToHTML;app.server.renderErrorToHTML = function(err, req, res, pathname, query) {    if (res.statusCode == 404) {        // handle the 404 however you like        return null;    } else {        return errorRenderer.apply(this, arguments);    }};