ProvenPin Install

Next.js middleware + Supabase SSR session refresh: working versions (tested 2026-10-15)

Refresh Supabase auth cookies in Next.js middleware with @supabase/ssr and redirect signed-out users away from protected routes.

passed3 passed · 0 failed2026-10-15 13:09 UTC
Status
passed
Last passed
2026-10-15 13:09 UTC
Tests
3 / 3
Language
TypeScript
Runtime
node v22.23.3
pinned versions7
next@16.4.1@supabase/ssr@0.12.7@supabase/supabase-js@2.117.3react@19.3.1react-dom@19.3.1tsx@4.23.15@types/node@24.19.2
run it
npm install --no-audit --no-fund --ignore-scripts=false
npm test
test environment
node v22.23.3
linux 6.17.0-1022-azure
x64
runner: github-actions 38738874208

The code

Exactly the files that passed. Your agent can pull them with get_recipe("nextjs-supabase-auth-middleware") (install), or see them on GitHub.

package.json
{
  "name": "nextjs-supabase-auth-middleware",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "node --import tsx --test test/*.test.ts"
  },
  "dependencies": {
    "next": "16.4.1",
    "@supabase/ssr": "0.12.7",
    "@supabase/supabase-js": "2.117.3",
    "react": "19.3.1",
    "react-dom": "19.3.1"
  },
  "devDependencies": {
    "tsx": "4.23.15",
    "@types/node": "24.19.2"
  }
}
lib/supabase/middleware.ts
import { createServerClient } from "@supabase/ssr";
import { NextResponse, type NextRequest } from "next/server";

export async function updateSession(request: NextRequest) {
  let response = NextResponse.next({ request });
  const supabase = createServerClient(process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!, {
    cookies: {
      getAll: () => request.cookies.getAll(),
      setAll: (cookiesToSet) => {
        cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value));
        response = NextResponse.next({ request });
        cookiesToSet.forEach(({ name, value, options }) => response.cookies.set(name, value, options));
      },
    },
  });
  const { data: { user } } = await supabase.auth.getUser();
  if (!user && request.nextUrl.pathname.startsWith("/dashboard")) {
    const url = request.nextUrl.clone();
    url.pathname = "/login";
    return NextResponse.redirect(url);
  }
  return response;
}
middleware.ts
import type { NextRequest } from "next/server";
import { updateSession } from "./lib/supabase/middleware.ts";
export function middleware(request: NextRequest) { return updateSession(request); }
export const config = { matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"] };
test/middleware.test.ts
import { test, before, after } from "node:test";
import assert from "node:assert/strict";
import http from "node:http";
import { NextRequest } from "next/server";

// Local mock of the Supabase Auth API so the test runs offline.
let server: http.Server;
before(async () => {
  server = http.createServer((req, res) => {
    const auth = req.headers.authorization ?? "";
    res.setHeader("content-type", "application/json");
    if (req.url?.startsWith("/auth/v1/user") && auth === "Bearer good-token") {
      res.end(JSON.stringify({ id: "u1", aud: "authenticated", email: "[email protected]", app_metadata: {}, user_metadata: {}, created_at: "2026-01-01T00:00:00Z" }));
    } else { res.statusCode = 401; res.end(JSON.stringify({ code: 401, msg: "invalid JWT" })); }
  });
  await new Promise<void>((r) => server.listen(0, r));
  const port = (server.address() as any).port;
  process.env.NEXT_PUBLIC_SUPABASE_URL = `http://127.0.0.1:${port}`;
  process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = "anon";
});
after(() => server.close());

const { middleware } = await import("../middleware.ts");

function sessionCookie(token: string) {
  const session = { access_token: token, refresh_token: "r", token_type: "bearer", expires_in: 3600, expires_at: Math.floor(Date.now() / 1000) + 3600, user: { id: "u1" } };
  return "base64-" + Buffer.from(JSON.stringify(session)).toString("base64url");
}

test("signed-out user is redirected from /dashboard", async () => {
  const res = await middleware(new NextRequest("http://localhost/dashboard"));
  assert.equal(res.status, 307);
  assert.match(res.headers.get("location")!, /\/login$/);
});
test("public pages pass through when signed out", async () => {
  const res = await middleware(new NextRequest("http://localhost/"));
  assert.equal(res.status, 200);
});
test("signed-in user reaches /dashboard", async () => {
  const req = new NextRequest("http://localhost/dashboard", { headers: { cookie: `sb-127-auth-token=${sessionCookie("good-token")}` } });
  const res = await middleware(req);
  assert.equal(res.status, 200);
});

Connect to ProvenPin

Add the free MCP server so your agent can pull this recipe and others like it. Same setup as the docs.

terminal
claude mcp add --transport http provenpin https://mcp.provenpin.com/mcp

Any other MCP client: Streamable HTTP at https://mcp.provenpin.com/mcp. No API key, no signup.