-
Notifications
You must be signed in to change notification settings - Fork 0
/
next.config.js
386 lines (359 loc) · 10.9 KB
/
next.config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
// @ts-check
/* eslint-disable max-lines */
/**
* Next.js Configuration
*
* @type {import('next').NextConfig}
*
* @see https://github.com/cyrilwanner/next-compose-plugins
* @see https://github.com/natterstefan/next-with-sentry/blob/main/next.config.js
*/
const { withSentryConfig } = require('@sentry/nextjs')
const { withPlugins, optional } = require('next-compose-plugins')
const withPWA = require('next-pwa')
const { PHASE_DEVELOPMENT_SERVER } = require('next/constants')
const VERCEL = 'VERCEL'
const NETLIFY = 'NETLIFY'
const AMPLIFY = 'AMPLIFY'
const LOCALHOST = 'LOCALHOST'
const detectPlatform = () => {
if (process.env.VERCEL === '1') {
return VERCEL
} else if (process.env.NETLIFY === 'true') {
return NETLIFY
} else if (process.env.CODEBUILD_CI === 'true') {
return AMPLIFY
}
return LOCALHOST // might also be Github CI
}
/* const buildId = `${Date.now()}` */
/* const generateBuildId = async () => buildId */
/*
* Security Header stuff
* @see {@link https://scotthel.me/cspcheatsheet}
* Thanks @ https://github.com/timlrx/tailwind-nextjs-starter-blog/blob/master/next.config.js
*
* You might need to insert additional domains in script-src if you are using external services
* @see {@link https://report-uri.com/home/generate}
*/
const ContentSecurityPolicy = `
default-src 'self';
script-src 'self' 'unsafe-eval' 'unsafe-inline';
script-src-elem 'self' data:;
style-src 'self' *.googleapis.com 'unsafe-inline';
img-src * blob: data:;
font-src 'self' data: fonts.gstatic.com;
frame-src 'self' *.youtube-nocookie.com;
sandbox allow-same-origin allow-scripts;
connect-src *;
media-src 'none';
`
/* upgrade-insecure-requests */
const PermissionsPolicy = `
accelerometer=(),
autoplay=(self "https://www.youtube-nocookie.com"),
camera=(),
display-capture=(),
document-domain=(self),
encrypted-media=(),
fullscreen=(self "https://www.youtube-nocookie.com"),
geolocation=(),
gyroscope=(),
interest-cohort=(),
magnetometer=(),
microphone=(),
midi=(),
payment=(),
picture-in-picture=(),
publickey-credentials-get=(),
sync-xhr=(),
usb=(),
screen-wake-lock=(),
xr-spatial-tracking=()
`
const securityHeaders = [
{
key: 'X-DNS-Prefetch-Control',
value: 'on',
},
{
key: 'Strict-Transport-Security',
value: 'max-age=63072000; includeSubDomains; preload',
},
{
key: 'X-XSS-Protection',
value: '1; mode=block',
},
{
key: 'X-Content-Type-Options',
value: 'nosniff',
},
{
key: 'X-Frame-Options',
value: 'DENY',
},
{
key: 'Referrer-Policy',
value: 'strict-origin-when-cross-origin',
},
{
key: 'Content-Security-Policy',
value: ContentSecurityPolicy.replace(/\n/gu, ''),
},
{
key: 'Permissions-Policy',
value: PermissionsPolicy.replace(/\n/gu, ''),
},
]
/**
* @type {import('next/dist/server/config').NextConfig}
*/
const nextConfiguration = {
amp: {
/* canonicalBase: '', */
},
compiler: {
reactRemoveProperties: true,
removeConsole: true,
},
env: {
NEXT_PUBLIC_SENTRY_DSN:
detectPlatform() === LOCALHOST
? undefined
: 'https://[email protected]/5842378',
platform: detectPlatform(),
},
eslint: {
/*
* Warning: Dangerously allow production builds to successfully complete even if
* your project has ESLint errors. ... I don't want a production dependency on eslint
*/
ignoreDuringBuilds: true,
},
// @see {@link https://github.com/vercel/next.js/blob/canary/packages/next/server/config-shared.ts#L130}
experimental: {
browsersListForSwc: true,
legacyBrowsers: false,
/* disablePostcssPresetEnv: boolean */
/* styledComponents?: boolean */
/* swcFileReading?: boolean */
/* cpus?: number */
/* sharedPool?: boolean */
/* plugins?: boolean */
/* profiling?: boolean */
/* isrFlushToDisk?: boolean */
/* reactMode?: 'legacy' | 'concurrent' | 'blocking' */
/* workerThreads?: boolean */
/* pageEnv?: boolean */
/* optimizeImages?: boolean */
/* optimizeCss?: boolean */
/* scrollRestoration?: boolean */
/* externalDir?: boolean */
/* conformance?: boolean */
},
/*
* amp?: {
* optimizer?: any
* validator?: string
* skipValidation?: boolean
* }
*/
/* reactRoot?: boolean */
/* disableOptimizedLoading?: boolean */
/* gzipSize?: boolean */
/* craCompat?: boolean */
/* esmExternals?: boolean | 'loose' */
/* isrMemoryCacheSize?: number */
/* concurrentFeatures?: boolean */
/* serverComponents?: boolean */
/* fullySpecified?: boolean */
/* urlImports?: NonNullable<webpack5.Configuration['experiments']>['buildHttp'] */
/* outputFileTracingRoot?: string */
/* outputStandalone?: boolean */
/* }, */
future: {},
/*
* @see {@link https://nextjs.org/docs/api-reference/next.config.js/configuring-the-build-id}
* @see {@link https://levelup.gitconnected.com/how-to-deploy-next-js-on-multiple-servers-3b493d4ce0e9}
*/
/* generateBuildId: () => `build-{Date.now()}`, */
// eslint-disable-next-line require-await
headers: async () => [
{
// Apply these headers to all routes in the application
headers: securityHeaders,
// Because of i18n routing I have to use "/:path*" instead of "/(.*)"
source: '/:path*',
},
{
// CORS headers, @see {@link https://ieftimov.com/post/deep-dive-cors-history-how-it-works-best-practices/}
headers: [
// the next line is an anti-pattern with 'Access-Control-Allow-Origing: *'
/* { key: "Access-Control-Allow-Credentials", value: "true" }, */
{ key: 'Access-Control-Allow-Origin', value: '*' },
{
key: 'Access-Control-Allow-Methods',
value: 'GET,OPTIONS,PATCH,DELETE,POST,PUT',
},
{
key: 'Access-Control-Allow-Headers',
value:
'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version',
},
],
// api routes are not localized
locale: false,
// matching all localized API routes, but not routes like '/api/hello'
source: '/api/:path*',
},
],
i18n: {
defaultLocale: 'en',
locales: ['en', 'de', 'es', 'fr', 'it'],
},
/*
* next.js font optimization breaks the link element insofar that there is no 'url' property, which my
* html linter complains about. unfortunately it's not possible to disable the linter because next.js
* puts the updated code at the top of the document head. I should re-enable font-optimization for production
* but will keep it disabled for now to get the linter feedback.
*/
optimizeFonts: false,
poweredByHeader: false,
/*
* publicRuntimeConfig: {
* dns: process.env.SENTRY_DSN || process.env.NEXT_PUBLIC_SENTRY_DSN,
* },
*/
reactStrictMode: true,
swcMinify: true,
webpack: (
/** @type {{ plugins: any[]; }} */ config,
/** @type {{ dev: any; isServer: any; }} */ { dev, isServer }
) => {
/* { buildId, dev, isServer, defaultLoaders, webpack } = options */
if (!dev && !isServer) {
/*
* Replace React with Preact only in client production build
* @see {@link https://github.com/timlrx/tailwind-nextjs-starter-blog/blob/master/next.config.js}
*/
Object.assign(config.resolve.alias, {
react: 'preact/compat',
'react-dom': 'preact/compat',
'react/jsx-runtime.js': 'preact/compat/jsx-runtime',
})
}
return config
},
}
/**
* Plugins go here
* params: function, configuration?: object, phases?: array
*
* I don't want to have 'bundle-analyzer' loaded in production at all
* so I added this check for an env var
*/
const plugins = () =>
process.env.ANALYZE === 'true'
? [
[
optional(() =>
require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
})
),
{
/* optional configuration */
},
['!', PHASE_DEVELOPMENT_SERVER],
],
[
withPWA,
{
pwa: {
/* additionalManifestEntries: [ */
/* '/', */
/* '/map', */
/* '/collection', */
/* '/offline', */
/* ].map(url => ({ */
/* revision: buildId, */
/* url, */
/* })), */
dest: 'public',
disable: process.env.NODE_ENV === 'development',
/* dontCacheBustURLsMatching: /^\/_next\/static\/.* /i, */
/* register: false, */
/* skipWaiting: false, */
/* swSrc: 'utils/serviceWorker.ts', */
},
},
],
]
: [
withPWA,
{
pwa: {
/* additionalManifestEntries: [ */
/* '/', */
/* '/map', */
/* '/collection', */
/* '/offline', */
/* ].map(url => ({ */
/* revision: buildId, */
/* url, */
/* })), */
dest: 'public',
disable: process.env.NODE_ENV === 'development',
/* dontCacheBustURLsMatching: /^\/_next\/static\/.* /i, */
/* register: false, */
/* skipWaiting: false, */
/* swSrc: 'utils/serviceWorker.ts', */
},
},
]
const nextPluginConfiguration = withPlugins(plugins(), nextConfiguration)
/*
* Set a custom webpack configuration to use Next.js app with Sentry.
*
* @see https://nextjs.org/docs/api-reference/next.config.js/introduction
* @see https://docs.sentry.io/platforms/javascript/guides/nextjs/
* @see https://blog.sentry.io/2020/08/04/enable-suspect-commits-unminify-js-and-track-releases-with-vercel-and-sentry
*/
const SentryWebpackPluginOptions = {
/*
* Additional config options for the Sentry Webpack plugin. Keep in mind that
* the following options are set automatically, and overriding them is not
* recommended:
* release, url, org, project, authToken, configFile, stripPrefix,
* urlPrefix, include, ignore
*/
/*
* Modify the event here
* can use this to improve privacy, eg. to disable error reporting if user not d'accord
* @see https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/filtering/
*/
beforeSend(event) {
if (event.user) {
// Don't send user's email address
delete event.user.email
}
return event
},
debug: true,
/* dryRun: process.env.NODE_ENV === 'development', */
dryRun: true,
silent: true, // Suppresses all logs
/*
* For all available options, see:
* https://github.com/getsentry/sentry-webpack-plugin#options.
*/
}
/*
* Make sure adding Sentry options is the last code to run before exporting, to
* ensure that your source maps include changes from all other Webpack plugins
*/
module.exports = withSentryConfig(
nextPluginConfiguration,
SentryWebpackPluginOptions
)
/* eslint-enable max-lines */