11import { defineNuxtModule , addPlugin , createResolver , addImportsDir , addServerHandler } from '@nuxt/kit'
2- import { sha256 } from 'ohash '
2+ import { join } from 'pathe '
33import { defu } from 'defu'
4+ import { randomUUID } from 'uncrypto'
5+ import { writeFile , readFile } from 'node:fs/promises'
46
57// Module options TypeScript interface definition
68export interface ModuleOptions { }
@@ -12,14 +14,20 @@ export default defineNuxtModule<ModuleOptions>({
1214 } ,
1315 // Default configuration options of the Nuxt module
1416 defaults : { } ,
15- setup ( options , nuxt ) {
17+ async setup ( options , nuxt ) {
1618 const resolver = createResolver ( import . meta. url )
1719
18- if ( ! process . env . NUXT_SESSION_PASSWORD && ! nuxt . options . _prepare ) {
19- const randomPassword = sha256 ( `${ Date . now ( ) } ${ Math . random ( ) } ` ) . slice ( 0 , 32 )
20- process . env . NUXT_SESSION_PASSWORD = randomPassword
21- console . warn ( 'No session password set, using a random password, please set NUXT_SESSION_PASSWORD in your .env file with at least 32 chars' )
22- console . log ( `NUXT_SESSION_PASSWORD=${ randomPassword } ` )
20+ // Generate the session password
21+ if ( nuxt . options . dev && ! process . env . NUXT_SESSION_PASSWORD ) {
22+ process . env . NUXT_SESSION_PASSWORD = randomUUID ( ) . replace ( / - / g, '' )
23+ // Add it to .env
24+ const envPath = join ( nuxt . options . rootDir , '.env' )
25+ const envContent = await readFile ( envPath , 'utf-8' ) . catch ( ( ) => '' )
26+ if ( ! envContent . includes ( 'NUXT_SESSION_PASSWORD' ) ) {
27+ await writeFile ( envPath , `${ envContent ? envContent + '\n' : envContent } NUXT_SESSION_PASSWORD=${ process . env . NUXT_SESSION_PASSWORD } ` , 'utf-8' )
28+ }
29+ } else if ( ! nuxt . options . _prepare && ! process . env . NUXT_SESSION_PASSWORD ) {
30+ throw new Error ( 'NUXT_SESSION_PASSWORD environment variable is not set' )
2331 }
2432
2533 nuxt . options . alias [ '#auth-utils' ] = resolver . resolve ( './runtime/types/index' )
0 commit comments