Skip to content

Commit

Permalink
fix how to append multiple cookies
Browse files Browse the repository at this point in the history
  • Loading branch information
Yo-mah-Ya committed Dec 21, 2023
1 parent c2df1bf commit a063707
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
21 changes: 17 additions & 4 deletions app/(auth)/uuid.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
import { cookies } from 'next/headers'
import { NextResponse } from 'next/server'
import type { Session } from '@supabase/supabase-js'
import type { NextResponse } from 'next/server'

const cookieName = 'user_uuid'

export const getUuid = () => cookies().get(cookieName)?.value ?? undefined

export const setUuid = (res: NextResponse, session: Session): NextResponse => {
res.cookies.set(cookieName, session.user.id)
return res
export const setUuidWithHeaders = (
headers: Headers,
session: Session
): Headers => {
headers.append(
'set-cookie',
NextResponse.next()
.cookies.set(cookieName, session.user.id, {
httpOnly: true,
sameSite: 'lax',
maxAge: 60 * 60 * 24, // 24 hours
path: '/'
})
.toString()
)
return headers
}
11 changes: 7 additions & 4 deletions middleware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NextResponse, type NextRequest } from 'next/server'
import { NextResponse, NextRequest } from 'next/server'
import { createClient } from '@/(auth)/supabase/middleware'
import { setUuid } from '@/(auth)/uuid'
import { setUuidWithHeaders } from '@/(auth)/uuid'

export const config = {
matcher: [
Expand Down Expand Up @@ -32,12 +32,15 @@ export async function middleware(request: NextRequest) {
request.nextUrl.pathname.startsWith('/signup')
) {
if (session) {
return setUuid(NextResponse.redirect(new URL('/', request.url)), session)
return NextResponse.redirect(new URL('/', request.url))
}
return response
}
if (error || !session) {
return NextResponse.redirect(new URL(signinUri, request.url))
}
return setUuid(response, session)

return NextResponse.next({
headers: setUuidWithHeaders(new Headers(request.headers), session)
})
}

0 comments on commit a063707

Please sign in to comment.