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
In my case, this extra stuff adds up to hundreds of megabytes.
I've got a partial solution that looks like this:
npm run build
node_modules, .next, static, package.json, and a couple other things into itcd to the new folder and run npm prune --production to remove dev dependenciesThis 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?
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,
}
}
next build
.next/standalone
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With