Is it possible (and how) to add some kind of "bootstrap" file (file with side-effects) as a very first file to be included in all APIs in Next.js?
The original use-case is that I've winston logger in a file which I have to put in all API endpoints, but this is quite poor DX. I just want to say "hey, put this file before all endpoints, so I know (in this case logger) everything is setup".
Thanks
So, I've found the solution in a custom webpack configuration:
import withPlugins from 'next-compose-plugins';
import { patchWebpackConfig } from 'next-global-css';
import images from 'next-images';
import withTM from 'next-transpile-modules';
import { merge } from 'webpack-merge';
export default withPlugins([
images,
withTM([]),
], {
swcMinify: true,
images: {
formats: ['image/avif', 'image/webp']
},
productionBrowserSourceMaps: false,
// experimental: {
// outputStandalone: true,
// },
webpack: (config, {
webpack,
buildId,
isServer,
...options
}) => {
config.plugins.push(
new webpack.DefinePlugin({
'process.env.BUILD_ID': JSON.stringify(buildId),
}),
);
if (isServer) {
return merge(config, {
entry() {
return config.entry().then(entry => {
// this is the interesting part: prefix entry with a bootstrap file, in my case logger side-effect file
Object.keys(entry).map(key => {
entry[key] = {import: ['./src/service/bootstrap.ts', ...entry[key]]};
});
return entry;
});
}
});
}
return patchWebpackConfig(config, options);
},
reactStrictMode: true,
staticPageGenerationTimeout: 15,
});