I'm currently building an e-commerce (Shopify, BigCommerce, etc.) extension using Node.js, Koa, React, and Next.js.
As part of the codebase, I have URL methods that must only be executed on the server-side. There should be no page generated for the URL. However, Next.js always requires a page to be generated.
Is there a way to only have Next.js simply invoke the URL method rather than generate a page? For example, /app/auth
should not generate a page, but instead execute server code. However, /app/dashboard
should generate a page.
I'm aware of using useFileSystemPublicRoutes
as a way to prevent this behavior. However, I found that it's quite wonky since it also needs client code.
However, Next.js always requires a page to be generated
No, That's not true, you can use custom server an decide if a route should or should not render a page.
A simple example with express.js:
rendere a page :
server.get('/my-page', (req, res) => {
return app.render(req, res, '/mypage', {...req.params, ...req.query})
})
An api endpoint :
server.post("/my-endpoint", async (req, res) => {
res.json({});
});
Note that to run the custom server you'll need to update the scripts in package.json with something like this :
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
If you are using Koa.js there is an official example for custom server with koa here