Next.js has a catch-all route that will ultimately read from the file system.
Because of this, its not possible to use the technique nextjs uses to know if a route exists:
Technique: https://github.com/zeit/next.js/blob/0c8dca6f9753ddf70226ee0e3835a6c03cf4480a/server/index.js#L279
Failure example in custom routes:
https://zeit-community.slack.com/files/U5HJRF98T/F7BBKQ3AS/-.js
One way to solve it is to expose a method that does the fs check in the router, or registering pages in server startup so app.router.pages returns properly.
I'll add some clarity to this issue by providing a use case.
A site should be able to have some of its top-level pages be static and other pages use a dynamic page template (which would fetch data from some kind of CMS).
For example, example.com/about would use next's handle method to send a request to the static pages/about.js template. Then, example.com/some-cool-event would use next's render method to send a request to the dynamic pages/event.js template.
The problem seems to be that there's no way to reliably detect if next would successfully route a request using the handle method from within a custom route handler.
Some pseudo-code to demonstrate the general idea:
server.get('*', (req, res) => {
if (app.nextWouldHandleRoute(req)) {
return handle(req, res)
} else {
const actualPage = '/event'
const queryParams = { id: /* pull ID out of request URL */ }
return app.render(req, res, actualPage, queryParams)
}
})
I am willing to write a failing example project for next.js on this, though I'm not confident on what would be the proper solution in the code base.
The problem with this approach is that the server itself is not aware of the routes that are going to be served.
Maybe this will be solved when we land support filesystem dynamic routes.
Most helpful comment
I'll add some clarity to this issue by providing a use case.
A site should be able to have some of its top-level pages be static and other pages use a dynamic page template (which would fetch data from some kind of CMS).
For example, example.com/about would use next's
handlemethod to send a request to the staticpages/about.jstemplate. Then, example.com/some-cool-event would use next'srendermethod to send a request to the dynamicpages/event.jstemplate.The problem seems to be that there's no way to reliably detect if next would successfully route a request using the
handlemethod from within a custom route handler.Some pseudo-code to demonstrate the general idea: