5b48db23b1
### What? [1] Add protected page [2] Add pending state ### Why? [1] People using incorrect ways to protect pages [2] No feedback that the login page is doing anything when buttons clicked ### How? [1] Redirect user to protected page after successful authentication [2] Use useFormStatus to determine whether the form is in a pending state --------- Co-authored-by: Sam Ko <sam@vercel.com>
78 lines
2.3 KiB
TypeScript
78 lines
2.3 KiB
TypeScript
import { createServerClient, type CookieOptions } from "@supabase/ssr";
|
|
import { type NextRequest, NextResponse } from "next/server";
|
|
|
|
export const updateSession = async (request: NextRequest) => {
|
|
// This `try/catch` block is only here for the interactive tutorial.
|
|
// Feel free to remove once you have Supabase connected.
|
|
try {
|
|
// Create an unmodified response
|
|
let response = NextResponse.next({
|
|
request: {
|
|
headers: request.headers,
|
|
},
|
|
});
|
|
|
|
const supabase = createServerClient(
|
|
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
|
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
|
|
{
|
|
cookies: {
|
|
get(name: string) {
|
|
return request.cookies.get(name)?.value;
|
|
},
|
|
set(name: string, value: string, options: CookieOptions) {
|
|
// If the cookie is updated, update the cookies for the request and response
|
|
request.cookies.set({
|
|
name,
|
|
value,
|
|
...options,
|
|
});
|
|
response = NextResponse.next({
|
|
request: {
|
|
headers: request.headers,
|
|
},
|
|
});
|
|
response.cookies.set({
|
|
name,
|
|
value,
|
|
...options,
|
|
});
|
|
},
|
|
remove(name: string, options: CookieOptions) {
|
|
// If the cookie is removed, update the cookies for the request and response
|
|
request.cookies.set({
|
|
name,
|
|
value: "",
|
|
...options,
|
|
});
|
|
response = NextResponse.next({
|
|
request: {
|
|
headers: request.headers,
|
|
},
|
|
});
|
|
response.cookies.set({
|
|
name,
|
|
value: "",
|
|
...options,
|
|
});
|
|
},
|
|
},
|
|
},
|
|
);
|
|
|
|
// This will refresh session if expired - required for Server Components
|
|
// https://supabase.com/docs/guides/auth/server-side/nextjs
|
|
await supabase.auth.getUser();
|
|
|
|
return response;
|
|
} catch (e) {
|
|
// If you are here, a Supabase client could not be created!
|
|
// This is likely because you have not set up environment variables.
|
|
// Check out http://localhost:3000 for Next Steps.
|
|
return NextResponse.next({
|
|
request: {
|
|
headers: request.headers,
|
|
},
|
|
});
|
|
}
|
|
};
|