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"