forked from npmx-dev/npmx.dev
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimage-proxy.ts
More file actions
41 lines (36 loc) · 1.3 KB
/
image-proxy.ts
File metadata and controls
41 lines (36 loc) · 1.3 KB
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
import { defineNuxtModule, useNuxt } from 'nuxt/kit'
import process from 'node:process'
import { join } from 'node:path'
import { appendFileSync, existsSync, readFileSync } from 'node:fs'
import { randomUUID } from 'node:crypto'
/**
* Auto-generates `NUXT_IMAGE_PROXY_SECRET` for local development if it is not
* already set. The secret is used to HMAC-sign image proxy URLs so that only
* server-generated URLs are accepted by the proxy endpoint.
*
* In production, `NUXT_IMAGE_PROXY_SECRET` must be set as an environment variable.
*/
export default defineNuxtModule({
meta: {
name: 'image-proxy',
},
setup() {
const nuxt = useNuxt()
if (nuxt.options._prepare || process.env.NUXT_IMAGE_PROXY_SECRET) {
return
}
const envPath = join(nuxt.options.rootDir, '.env')
const hasSecret =
existsSync(envPath) && /^NUXT_IMAGE_PROXY_SECRET=/m.test(readFileSync(envPath, 'utf-8'))
if (!hasSecret) {
// eslint-disable-next-line no-console
console.info('Generating NUXT_IMAGE_PROXY_SECRET for development environment.')
const secret = randomUUID().replace(/-/g, '')
nuxt.options.runtimeConfig.imageProxySecret = secret
appendFileSync(
envPath,
`# generated by image-proxy module\nNUXT_IMAGE_PROXY_SECRET=${secret}\n`,
)
}
},
})