Search code examples
buildnext.js

Next.js CLI - is it possible to pre-build certain routes when running dev locally?


I'm part of an org with an enterprise app built on Next.js, and as it's grown the local dev experience has been degrading. The main issue is that our pages make several calls to /api routes on load, and those are built lazily when you run yarn dev, so you're always forced to sit and wait in the browser while that happens.

I've been thinking it might be better if we were able to actually pre-build all of the /api routes right away when yarn dev is run, so we'd get a better experience when the browser is opened. I've looked at the CLI docs but it seems the only options for dev are -p (port) and -H (host). I also don't think running yarn build first will work as I assume the build output is quite different between the build and dev commands.

Does anyone know if this is possible? Any help is appreciated, thank you!


Solution

  • I don't believe there's a way to prebuild them, but you can tell Next how long to keep them before discarding and rebuilding. Check out the onDemandEntries docs. We had a similar issue and solved it for a big project about a year ago with this in our next.config.js:

    const { PHASE_DEVELOPMENT_SERVER } = require("next/constants")
    
    module.exports = (phase, {}) => {
      let devOnDemandEntries = {}
      if (phase === PHASE_DEVELOPMENT_SERVER) {
        devOnDemandEntries = {
          // period (in ms) where the server will keep pages in the buffer
          maxInactiveAge: 300 * 1000,
          // number of pages that should be kept simultaneously without being disposed
          pagesBufferLength: 5,
        }
      }
      return {
        onDemandEntries,
        ...
      }
    }