auto-claude: subtask-1-3 - Add CSRF token generation to middleware
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
+34
-1
@@ -1,12 +1,45 @@
|
|||||||
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
import createMiddleware from 'next-intl/middleware';
|
import createMiddleware from 'next-intl/middleware';
|
||||||
import { locales, defaultLocale } from './i18n/config';
|
import { locales, defaultLocale } from './i18n/config';
|
||||||
|
import { randomBytes } from 'crypto';
|
||||||
|
|
||||||
export default createMiddleware({
|
const CSRF_TOKEN_COOKIE_NAME = 'csrf_token';
|
||||||
|
const CSRF_TOKEN_LENGTH = 32;
|
||||||
|
|
||||||
|
const intlMiddleware = createMiddleware({
|
||||||
locales,
|
locales,
|
||||||
defaultLocale,
|
defaultLocale,
|
||||||
localePrefix: 'always',
|
localePrefix: 'always',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export default function middleware(request: NextRequest) {
|
||||||
|
// Run the i18n middleware first
|
||||||
|
const response = intlMiddleware(request);
|
||||||
|
|
||||||
|
// Check if CSRF token exists in cookies
|
||||||
|
const existingToken = request.cookies.get(CSRF_TOKEN_COOKIE_NAME);
|
||||||
|
|
||||||
|
// Generate and set CSRF token if it doesn't exist
|
||||||
|
if (!existingToken) {
|
||||||
|
const newToken = randomBytes(CSRF_TOKEN_LENGTH).toString('base64url');
|
||||||
|
|
||||||
|
// Create a new response or clone the existing one
|
||||||
|
const finalResponse = response || NextResponse.next();
|
||||||
|
|
||||||
|
finalResponse.cookies.set(CSRF_TOKEN_COOKIE_NAME, newToken, {
|
||||||
|
httpOnly: true,
|
||||||
|
secure: process.env.NODE_ENV === 'production',
|
||||||
|
sameSite: 'strict',
|
||||||
|
maxAge: 60 * 60 * 24, // 24 hours
|
||||||
|
path: '/',
|
||||||
|
});
|
||||||
|
|
||||||
|
return finalResponse;
|
||||||
|
}
|
||||||
|
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
matcher: [
|
matcher: [
|
||||||
'/',
|
'/',
|
||||||
|
|||||||
Reference in New Issue
Block a user