Add documentation for iron-session pattern including session options and usage in server actions.
34 lines
808 B
Markdown
34 lines
808 B
Markdown
# Patroon: iron-session
|
|
|
|
## lib/session.ts
|
|
|
|
```ts
|
|
import { SessionOptions } from 'iron-session'
|
|
|
|
export interface SessionData {
|
|
userId: string
|
|
isDemo: boolean
|
|
}
|
|
|
|
export const sessionOptions: SessionOptions = {
|
|
password: process.env.SESSION_SECRET!,
|
|
cookieName: 'scrum4me-session',
|
|
cookieOptions: {
|
|
secure: process.env.NODE_ENV === 'production',
|
|
httpOnly: true,
|
|
sameSite: 'lax',
|
|
},
|
|
}
|
|
```
|
|
|
|
## Gebruik in Server Action of Route Handler
|
|
|
|
```ts
|
|
import { getIronSession } from 'iron-session'
|
|
import { cookies } from 'next/headers'
|
|
import { SessionData, sessionOptions } from '@/lib/session'
|
|
|
|
const session = await getIronSession<SessionData>(await cookies(), sessionOptions)
|
|
if (!session.userId) redirect('/login')
|
|
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }
|
|
```
|