Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a minimal deployment of a Next.js non-static app?

Tags:

npm

next.js

The way Next.JS documentation and other tutorials describe how to deploy a non-static app (i.e. one that you run with npm run start) seems to leave a lot of unnecessary stuff in the app. They say to just run npm run build, and then run npm run start and congrats, you're done!

This is strange to me because when other systems such as Webpack create a deployable version, it is much more minimal. By minimal I mean it doesn't contain

  • devDependencies in node_modules
  • unminified source files (mine are TypeScript)
  • other miscellaneous stuff like React Storybook stories, etc.

In my case, this extra stuff adds up to hundreds of megabytes.

I've got a partial solution that looks like this:

  1. Run npm run build
  2. Make a new folder and copy node_modules, .next, static, package.json, and a couple other things into it
  3. cd to the new folder and run npm prune --production to remove dev dependencies

This basically works but I'm not entirely happy with it. For one thing, node_modules still contains a lot of stuff that isn't needed. In a Webpack product this stuff would be ignored due to tree shaking. For another, I have a couple other app-specific folders I have to remember to copy over.

Why is this so hard? Is there a better way to do it?

like image 397
tom Avatar asked Jan 17 '20 06:01

tom


1 Answers

Starting from [email protected] you can create a standalone build that drops all unnecessary dependencies (bundle size is reduced by 70%-80%). To use it you can just set this in your next.config.js (as described here https://nextjs.org/docs/advanced-features/output-file-tracing#automatically-copying-traced-files-experimental)

module.exports = {
  experimental: {
    outputStandalone: true,
  }
}
  • Run next build
  • This will create a folder at .next/standalone
  • Then instead of next start you must use the server.js file generated in the .next/standalone folder node .next/standalone/server.js

if you are in a docker environment you should also copy the static folder

...
COPY ./next.config.js ./
COPY ./public ./public
COPY ./package.json ./package.json
COPY --chown=nextjs:nodejs ./.next/standalone ./
COPY --chown=nextjs:nodejs /.next/static ./.next/static
....

EXPOSE 3000

CMD ["node", "server.js"]
like image 117
dna Avatar answered Oct 18 '22 08:10

dna