Can I use webpack to bundle a Next.js custom server?

Viewed 461

When you implement a custom server with Next.js it isn't bundled in the production build. My question is (before I try), can a custom webpack config be used to bundle it?

My reason for wanting to do this is that I don't want to ship code in the production build.

EDIT: I'm working with Next.js 7.0.2 and Webpack 4.20.2 which is used by that. So this is the right link for customising the webpack config for that version.

1 Answers

Okay, so having experimented, it turns out you can add another entry to the existing Next.js webpack config but because the custom server needs different settings it's actually better to do it separately. I now have a build-server script that bundles the custom server to a folder called .server. I also added obfuscation to both that and the Next.js webpack config.

Here's my next-config.js:

const withCSS = require('@zeit/next-css')
const WebpackObfuscator = require('webpack-obfuscator')

module.exports = withCSS({
    poweredByHeader: false,
    webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
        if (process.env.NODE_ENV === 'production') {
            // Extend default config with obfuscation
            config.plugins.push(
                new WebpackObfuscator ({
                    rotateStringArray: true
                })
            )
        }

        // Important: return the modified config
        return config
    }
})

And here's my webpack.config.server.js:

const path = require('path')
const nodeExternals = require('webpack-node-externals')
const WebpackObfuscator = require('webpack-obfuscator')

// Config to build Express server and associated server-side code bundle
module.exports = {
    mode: 'production',
    target: 'node',
    entry: './server/server.js',
    externals: [nodeExternals()], // Ignore node_modules
    output: {
        path: path.resolve(__dirname, '.server'),
        filename: 'server.bundle.js',
    },
    plugins: [
        // Obfuscate the code
        new WebpackObfuscator ({
            rotateStringArray: true
        })
    ]
}

The build-server script is:

"build-server": "webpack --config ./webpack.config.server.js"
Related