Supabase Auth Middleware (supabase/middleware.ts)

giselle · auth, Auth / Identity, nextjs, supabase, middleware, server

Next.js middleware that injects a Supabase client, handles optional auth guards, and synchronizes cookies for server‑side requests.

// Source: https://github.com/mperkins0155/giselle | License: Apache-2.0 | Copyright 2024 ROUTE06, Inc
// Provided via justclaw.it.com; keep this notice with the code.
import type { User } from "@supabase/auth-js";
import { type NextRequest, NextResponse } from "next/server";
import { createServerClient } from "./create-server-client";

export const supabaseMiddleware = (
	guardCallback?: (
		user: User | null,
		request: NextRequest,
	) => Promise<NextResponse | undefined>,
) => {
	return async (request: NextRequest) => {
		// Dev safeguard: If Supabase env vars are not set locally, skip auth wiring
		if (
			!process.env.NEXT_PUBLIC_SUPABASE_URL ||
			!process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
		) {
			// Throw error in production if Supabase environment variables are missing
			if (proc

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search 40K more like it.

Get a free API key