chore: refactor middleware for better session handling

This commit is contained in:
javayhu 2025-04-28 19:08:52 +08:00
parent a73493a042
commit 460dae64e3
5 changed files with 43 additions and 12 deletions

View File

@ -20,6 +20,7 @@
"@ai-sdk/openai": "^1.1.13",
"@aws-sdk/client-s3": "^3.758.0",
"@aws-sdk/s3-request-presigner": "^3.758.0",
"@better-fetch/fetch": "^1.1.18",
"@content-collections/core": "^0.8.0",
"@content-collections/mdx": "^0.2.0",
"@content-collections/next": "^0.2.4",
@ -123,7 +124,6 @@
"use-intl": "^3.26.5",
"use-media": "^1.5.0",
"vaul": "^1.1.2",
"wretch": "^2.11.0",
"zod": "^3.24.2",
"zustand": "^5.0.3"
},

10
pnpm-lock.yaml generated
View File

@ -17,6 +17,9 @@ importers:
'@aws-sdk/s3-request-presigner':
specifier: ^3.758.0
version: 3.758.0
'@better-fetch/fetch':
specifier: ^1.1.18
version: 1.1.18
'@content-collections/core':
specifier: ^0.8.0
version: 0.8.0(typescript@5.7.3)
@ -673,6 +676,9 @@ packages:
'@better-fetch/fetch@1.1.12':
resolution: {integrity: sha512-B3bfloI/2UBQWIATRN6qmlORrvx3Mp0kkNjmXLv0b+DtbtR+pP4/I5kQA/rDUv+OReLywCCldf6co4LdDmh8JA==}
'@better-fetch/fetch@1.1.18':
resolution: {integrity: sha512-rEFOE1MYIsBmoMJtQbl32PGHHXuG2hDxvEd7rUHE0vCBoFQVSDqaVs9hkZEtHCxRoY+CljXKFCOuJ8uxqw1LcA==}
'@biomejs/biome@1.9.4':
resolution: {integrity: sha512-1rkd7G70+o9KkTn5KLmDYXihGoTaIGO9PIIN2ZB7UJxFrWw04CZHPYiMRjYsaDvVV7hP1dYNRLxSANLaBFGpog==}
engines: {node: '>=14.21.3'}
@ -6275,6 +6281,8 @@ snapshots:
'@better-fetch/fetch@1.1.12': {}
'@better-fetch/fetch@1.1.18': {}
'@biomejs/biome@1.9.4':
optionalDependencies:
'@biomejs/cli-darwin-arm64': 1.9.4
@ -8688,7 +8696,7 @@ snapshots:
better-call@0.3.3:
dependencies:
'@better-fetch/fetch': 1.1.12
'@better-fetch/fetch': 1.1.18
rou3: 0.5.1
uncrypto: 0.1.3
zod: 3.24.2

View File

@ -4,7 +4,14 @@
*/
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
const client = postgres(process.env.DATABASE_URL!);
const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
throw new Error('DATABASE_URL is not set');
}
// Disable prefetch as it is not supported for "Transaction" pool mode
const client = postgres(connectionString, { prepare: false });
const db = drizzle(client);
/**

3
src/lib/auth-types.ts Normal file
View File

@ -0,0 +1,3 @@
import type { auth } from './auth';
export type Session = typeof auth.$Infer.Session;

View File

@ -1,9 +1,8 @@
import { betterFetch } from '@better-fetch/fetch';
import createMiddleware from 'next-intl/middleware';
import { headers } from 'next/headers';
import { type NextRequest, NextResponse } from 'next/server';
import wretch from 'wretch';
import { LOCALES, routing } from './i18n/routing';
import type { auth } from './lib/auth';
import type { Session } from './lib/auth-types';
import {
DEFAULT_LOGIN_REDIRECT,
protectedRoutes,
@ -12,17 +11,31 @@ import {
const intlMiddleware = createMiddleware(routing);
/**
* 1. Next.js middleware
* https://nextjs.org/docs/app/building-your-application/routing/middleware
*
* 2. Better Auth middleware
* https://www.better-auth.com/docs/integrations/next#middleware
*
* In Next.js middleware, it's recommended to only check for the existence of a session cookie
* to handle redirection. To avoid blocking requests by making API or database calls.
*/
export default async function middleware(req: NextRequest) {
const { nextUrl } = req;
const { nextUrl, headers } = req;
console.log('>> middleware start, pathname', nextUrl.pathname);
// do not use getSession() here, it will cause error related to edge runtime
// const session = await getSession();
const session = await wretch(`${nextUrl.origin}/api/auth/get-session`)
// .headers({ cookie: headers.get('cookie') || '' })
.headers(await headers())
.get()
.json<typeof auth.$Infer.Session>();
const { data: session } = await betterFetch<Session>(
'/api/auth/get-session',
{
baseURL: req.nextUrl.origin,
headers: {
cookie: req.headers.get('cookie') || '', // Forward the cookies from the request
},
}
);
const isLoggedIn = !!session;
// console.log('middleware, isLoggedIn', isLoggedIn);