Unverified Commit 1da90c27 authored by Jon Meyers's avatar Jon Meyers Committed by GitHub

Clean up with-supabase example (#61799)

### What?

[1] Clean up `with-supabase` example following patterns from @leerob's
recent video on authentication
[2] Add images to matcher to reduce number of times a session is
refreshed
[3] Move instantiation of `cookieStore` into Supabase server helper

### Why?

[1] Make template easier to understand and use
[2] Reduce likelihood users will receive Auth Rate Limit Exceeded error
[3] Makes creating a Supabase client much simpler in Server Components,
Route Handlers and Server Actions

### How?

[1] Refactor middleware and its helper function
[2] Add image extensions to middleware matcher
[3] Call `cookies()` function from `createClient` helper - this should
still be in the [same execution
context](https://nextjs.org/docs/messages/dynamic-server-error) and
appears to work from my testing, but would be good to get the 👍 from
someone at Vercel
parent 13d8b140
import { createClient } from "@/utils/supabase/server"; import { createClient } from "@/utils/supabase/server";
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { cookies } from "next/headers";
export async function GET(request: Request) { export async function GET(request: Request) {
// The `/auth/callback` route is required for the server-side auth flow implemented // The `/auth/callback` route is required for the server-side auth flow implemented
// by the Auth Helpers package. It exchanges an auth code for the user's session. // by the SSR package. It exchanges an auth code for the user's session.
// https://supabase.com/docs/guides/auth/auth-helpers/nextjs#managing-sign-in-with-code-exchange // https://supabase.com/docs/guides/auth/server-side/nextjs
const requestUrl = new URL(request.url); const requestUrl = new URL(request.url);
const code = requestUrl.searchParams.get("code"); const code = requestUrl.searchParams.get("code");
if (code) { if (code) {
const cookieStore = cookies(); const supabase = createClient();
const supabase = createClient(cookieStore);
await supabase.auth.exchangeCodeForSession(code); await supabase.auth.exchangeCodeForSession(code);
} }
......
import Link from "next/link"; import Link from "next/link";
import { headers, cookies } from "next/headers"; import { headers } from "next/headers";
import { createClient } from "@/utils/supabase/server"; import { createClient } from "@/utils/supabase/server";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
...@@ -13,8 +13,7 @@ export default function Login({ ...@@ -13,8 +13,7 @@ export default function Login({
const email = formData.get("email") as string; const email = formData.get("email") as string;
const password = formData.get("password") as string; const password = formData.get("password") as string;
const cookieStore = cookies(); const supabase = createClient();
const supabase = createClient(cookieStore);
const { error } = await supabase.auth.signInWithPassword({ const { error } = await supabase.auth.signInWithPassword({
email, email,
...@@ -34,8 +33,7 @@ export default function Login({ ...@@ -34,8 +33,7 @@ export default function Login({
const origin = headers().get("origin"); const origin = headers().get("origin");
const email = formData.get("email") as string; const email = formData.get("email") as string;
const password = formData.get("password") as string; const password = formData.get("password") as string;
const cookieStore = cookies(); const supabase = createClient();
const supabase = createClient(cookieStore);
const { error } = await supabase.auth.signUp({ const { error } = await supabase.auth.signUp({
email, email,
......
...@@ -4,16 +4,13 @@ import { createClient } from "@/utils/supabase/server"; ...@@ -4,16 +4,13 @@ import { createClient } from "@/utils/supabase/server";
import ConnectSupabaseSteps from "@/components/ConnectSupabaseSteps"; import ConnectSupabaseSteps from "@/components/ConnectSupabaseSteps";
import SignUpUserSteps from "@/components/SignUpUserSteps"; import SignUpUserSteps from "@/components/SignUpUserSteps";
import Header from "@/components/Header"; import Header from "@/components/Header";
import { cookies } from "next/headers";
export default async function Index() { export default async function Index() {
const cookieStore = cookies();
const canInitSupabaseClient = () => { const canInitSupabaseClient = () => {
// This function is just for the interactive tutorial. // This function is just for the interactive tutorial.
// Feel free to remove it once you have Supabase connected. // Feel free to remove it once you have Supabase connected.
try { try {
createClient(cookieStore); createClient();
return true; return true;
} catch (e) { } catch (e) {
return false; return false;
......
import { createClient } from "@/utils/supabase/server"; import { createClient } from "@/utils/supabase/server";
import Link from "next/link"; import Link from "next/link";
import { cookies } from "next/headers";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
export default async function AuthButton() { export default async function AuthButton() {
const cookieStore = cookies(); const supabase = createClient();
const supabase = createClient(cookieStore);
const { const {
data: { user }, data: { user },
...@@ -14,8 +12,7 @@ export default async function AuthButton() { ...@@ -14,8 +12,7 @@ export default async function AuthButton() {
const signOut = async () => { const signOut = async () => {
"use server"; "use server";
const cookieStore = cookies(); const supabase = createClient();
const supabase = createClient(cookieStore);
await supabase.auth.signOut(); await supabase.auth.signOut();
return redirect("/login"); return redirect("/login");
}; };
......
...@@ -17,11 +17,9 @@ values ...@@ -17,11 +17,9 @@ values
const server = ` const server = `
import { createClient } from '@/utils/supabase/server' import { createClient } from '@/utils/supabase/server'
import { cookies } from 'next/headers'
export default async function Page() { export default async function Page() {
const cookieStore = cookies() const supabase = createClient()
const supabase = createClient(cookieStore)
const { data: notes } = await supabase.from('notes').select() const { data: notes } = await supabase.from('notes').select()
return <pre>{JSON.stringify(notes, null, 2)}</pre> return <pre>{JSON.stringify(notes, null, 2)}</pre>
......
import { NextResponse, type NextRequest } from "next/server"; import { type NextRequest } from "next/server";
import { createClient } from "@/utils/supabase/middleware"; import { updateSession } from "@/utils/supabase/middleware";
export async function middleware(request: NextRequest) { export async function middleware(request: NextRequest) {
try { return await updateSession(request);
// This `try/catch` block is only here for the interactive tutorial.
// Feel free to remove once you have Supabase connected.
const { supabase, response } = createClient(request);
// 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,
},
});
}
} }
export const config = { export const config = {
matcher: [ matcher: [
/* /*
* Match all request paths except for the ones starting with: * Match all request paths except:
* - _next/static (static files) * - _next/static (static files)
* - _next/image (image optimization files) * - _next/image (image optimization files)
* - favicon.ico (favicon file) * - favicon.ico (favicon file)
* - images - .svg, .png, .jpg, .jpeg, .gif, .webp
* Feel free to modify this pattern to include more paths. * Feel free to modify this pattern to include more paths.
*/ */
"/((?!_next/static|_next/image|favicon.ico).*)", "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
], ],
}; };
...@@ -59,3 +59,26 @@ export const createClient = (request: NextRequest) => { ...@@ -59,3 +59,26 @@ export const createClient = (request: NextRequest) => {
return { supabase, response }; return { supabase, response };
}; };
export const updateSession = async (request: NextRequest) => {
try {
// This `try/catch` block is only here for the interactive tutorial.
// Feel free to remove once you have Supabase connected.
const { supabase, response } = createClient(request);
// 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,
},
});
}
};
import { createServerClient, type CookieOptions } from "@supabase/ssr"; import { createServerClient, type CookieOptions } from "@supabase/ssr";
import { cookies } from "next/headers"; import { cookies } from "next/headers";
export const createClient = (cookieStore: ReturnType<typeof cookies>) => { export const createClient = () => {
const cookieStore = cookies();
return createServerClient( return createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment