A developer is working on a Next.js project with TypeScript and wants to ensure that stack traces correctly map to source files using source maps. Since this requires running Node with the --enable-source-maps flag, they attempted two different methods but didn't achieve the expected results.
First, they tried setting the NODE_OPTIONS environment variable to include --enable-source-maps. Then, they modified the start script in package.json like this:
"scripts": {
"start": "NODE_OPTIONS=\"--enable-source-maps\" next start"
}
Source maps are still not functioning as intended in stack traces. Any ideas?
You're on the right track with trying to enable source maps for your Next.js application. Let me help you get this working properly.
For browser source maps in production builds, you need to enable them in your next.config.js file 1:
// next.config.js
module.exports = {
productionBrowserSourceMaps: true,
}This will generate source maps during production builds that will be served automatically when requested by the browser 1. Note that this can increase build time and memory usage 1.
For server-side stack traces (Node.js), your approach with NODE_OPTIONS is correct, but there are a few things to check:
Make sure you're using single quotes instead of double quotes with the NODE_OPTIONS environment variable to avoid shell escaping issues.
tsconfig.json has source map generation enabled:{
"compilerOptions": {
"sourceMap": true,
// other options...
}
}// next.config.js
module.exports = {
productionBrowserSourceMaps: true,
webpack: (config, { dev, isServer }) => {
// Force source maps in development and production
if (!dev && !isServer) {
config.devtool = 'source-map';
}
return config;
},
}NODE_OPTIONS environment variable in your deployment settings as well.These changes should help you get proper source maps working for both client and server-side code in your Next.js application.