feat: add cookie helper for middlewares (#1275)

This commit is contained in:
Bereket Engida
2025-02-04 10:14:03 +03:00
committed by GitHub
parent 04ef8e8436
commit 2eca1daf4f
5 changed files with 120 additions and 34 deletions

View File

@@ -1,20 +1,9 @@
import { betterFetch } from "@better-fetch/fetch";
import { NextRequest, NextResponse } from "next/server";
import type { Session } from "./lib/auth-types";
import { getSessionCookie } from "better-auth";
export async function middleware(request: NextRequest) {
const { data: session } = await betterFetch<Session>(
"/api/auth/get-session",
{
baseURL: request.nextUrl.origin,
headers: {
//get the cookie from the request
cookie: request.headers.get("cookie") || "",
},
},
);
if (!session) {
const cookies = getSessionCookie(request);
if (!cookies) {
return NextResponse.redirect(new URL("/", request.url));
}
return NextResponse.next();