|
| 1 | +import { createServerClient } from "@supabase/ssr"; |
| 2 | +import { NextResponse, type NextRequest } from "next/server"; |
| 3 | + |
| 4 | +// Inspired by https://supabase.com/ui/docs/nextjs/password-based-auth |
| 5 | + |
| 6 | +export const updateSession = async (request: NextRequest) => { |
| 7 | + const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; |
| 8 | + const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY; |
| 9 | + |
| 10 | + if (!supabaseUrl || !supabaseKey) { |
| 11 | + throw new Error("Missing required Supabase environment variables"); |
| 12 | + } |
| 13 | + |
| 14 | + let supabaseResponse = NextResponse.next({ request }); |
| 15 | + |
| 16 | + const supabase = createServerClient(supabaseUrl, supabaseKey, { |
| 17 | + cookies: { |
| 18 | + getAll() { |
| 19 | + return request.cookies.getAll(); |
| 20 | + }, |
| 21 | + setAll(cookiesToSet) { |
| 22 | + cookiesToSet.forEach(({ name, value }) => |
| 23 | + request.cookies.set(name, value), |
| 24 | + ); |
| 25 | + supabaseResponse = NextResponse.next({ |
| 26 | + request, |
| 27 | + }); |
| 28 | + cookiesToSet.forEach(({ name, value, options }) => |
| 29 | + supabaseResponse.cookies.set(name, value, options), |
| 30 | + ); |
| 31 | + }, |
| 32 | + }, |
| 33 | + }); |
| 34 | + |
| 35 | + // Do not run code between createServerClient and |
| 36 | + // supabase.auth.getUser(). A simple mistake could make it very hard to debug |
| 37 | + // issues with users being randomly logged out. |
| 38 | + |
| 39 | + // IMPORTANT: DO NOT REMOVE auth.getUser() |
| 40 | + |
| 41 | + const { |
| 42 | + data: { user }, |
| 43 | + } = await supabase.auth.getUser(); |
| 44 | + |
| 45 | + if ( |
| 46 | + !user && |
| 47 | + !request.nextUrl.pathname.startsWith("/login") && |
| 48 | + !request.nextUrl.pathname.startsWith("/auth") |
| 49 | + ) { |
| 50 | + // no user, potentially respond by redirecting the user to the login page |
| 51 | + const url = request.nextUrl.clone(); |
| 52 | + url.pathname = "/auth/login"; |
| 53 | + return NextResponse.redirect(url); |
| 54 | + } |
| 55 | + |
| 56 | + // IMPORTANT: You *must* return the supabaseResponse object as it is. |
| 57 | + // If you're creating a new response object with NextResponse.next() make sure to: |
| 58 | + // 1. Pass the request in it, like so: |
| 59 | + // const myNewResponse = NextResponse.next({ request }) |
| 60 | + // 2. Copy over the cookies, like so: |
| 61 | + // myNewResponse.cookies.setAll(supabaseResponse.cookies.getAll()) |
| 62 | + // 3. Change the myNewResponse object to fit your needs, but avoid changing |
| 63 | + // the cookies! |
| 64 | + // 4. Finally: |
| 65 | + // return myNewResponse |
| 66 | + // If this is not done, you may be causing the browser and server to go out |
| 67 | + // of sync and terminate the user's session prematurely! |
| 68 | + |
| 69 | + return supabaseResponse; |
| 70 | +}; |
0 commit comments