backend/middlewares/next/index.js (view raw)
1const next = require('next');
2
3module.exports = strapi => ({
4 async initialize() {
5 if (process.env.NODE_ENV !== 'production') return;
6
7 const app = next({
8 dev: process.env.NODE_ENV !== 'production',
9 ...strapi.config.middleware.settings.next,
10 });
11 const handle = app.getRequestHandler();
12
13 // Prepare NextJS server
14 await app.prepare();
15
16 // Serve NextJS on index
17 strapi.router.get('/', ctx => handle(ctx.req, ctx.res));
18
19 // Serve NextJS app on non-handled endpoints
20 strapi.app.use(async (ctx, nxt) => {
21 await nxt();
22
23 if (ctx.response.status === 404) {
24 await handle(ctx.req, ctx.res);
25 }
26 });
27 },
28});