node.jsexpressnext.js

How to serve Next.js SSG files with Express.js


When doing next export, a folder called build will be generated. Currently I want to serve these static files using Express.js, here is the code:

app.use('/', express.static(path.join(__dirname, 'build')));
app.get('*', (req, res) => {
  console.log(req.path);
  res.sendFile(path.resolve(__dirname, 'build', 'index.html'));
});
app.listen(PORT, () => console.log('App is running!'));

The problem here is when accessing paths other than / such as /blog, it will redirect to / file (index.html), should I type in the routes one by one for each route, or is there another way to serve next SSG files with express?


Solution

  • I managed to do something like this:

    const dir = __dirname;
    const sendFile = (file) => (req, res) => res.sendFile(path.resolve(dir, 'build', file));
    const pathMap = new Set([
      '/settings', '/home' // All available static paths
    ]);
    
    // For static files such as icons/images/etc
    app.use(express.static(path.join(dir, 'build')));
    
    // Nextjs dynamic routing
    app.get('/blog/:blogID', sendFile('blog/[blogID].html'));
    app.get('/category/:category', sendFile('category/[category].html'));
    
    // Other paths, check whether to show page or 404(not found) page
    app.get('*', (req, res) => {
      const p = req.path;
      if (pathMap.has(p)) res.sendFile(path.resolve(dir, 'build', `${p.slice(1)}.html`));
      else res.sendFile(path.resolve(dir, 'build', '404.html'));
    });