@@ -8,21 +8,7 @@ import { getBackendUrl } from "./global/utils";
88import { internalAccessCookieName } from "./global/api" ;
99
1010export const onRequest : MiddlewareHandler = async ( context , next ) => {
11- const nextResponse = await next ( ) ;
12-
13- const EXTRA_HEADERS = {
14- "X-Content-Type-Options" : "nosniff" ,
15- "Referrer-Policy" : "strict-origin-when-cross-origin" ,
16- "Permissions-Policy" :
17- "camera=(), microphone=(), geolocation=(), payment=()" ,
18- "X-Frame-Options" : "DENY" ,
19- "Strict-Transport-Security" : "max-age=31536000; includeSubDomains" ,
20- } ;
21-
22- for ( const [ key , value ] of Object . entries ( EXTRA_HEADERS ) ) {
23- nextResponse . headers . set ( key , value ) ;
24- }
25-
11+ // ===== AUTHENTICATION MUST HAPPEN BEFORE RENDERING =====
2612 let internalAccessToken = null ;
2713
2814 const env =
@@ -40,6 +26,7 @@ export const onRequest: MiddlewareHandler = async (context, next) => {
4026 const backendUrl = getBackendUrl ( ) ;
4127 const protectedStaffRoutes = [ / ^ \/ s u p p o r t .* / , / ^ \/ s t o r i e s .* / ] ;
4228
29+ // Validate and set auth cookie BEFORE rendering the page
4330 if ( ! context . cookies . get ( internalAccessCookieName ) ?. value ) {
4431 if ( internalAccessToken ) {
4532 try {
@@ -71,14 +58,15 @@ export const onRequest: MiddlewareHandler = async (context, next) => {
7158 } ) ;
7259 } catch ( e : unknown ) {
7360 console . error ( "sign-in error" , e ) ;
74- context . redirect ( Routes . SignInError ) ;
61+ return context . redirect ( Routes . SignInError ) ;
7562 }
7663 } else {
7764 console . error ( "internalAccessToken not set" , backendUrl ) ;
78- context . redirect ( Routes . SignInError ) ;
65+ return context . redirect ( Routes . SignInError ) ;
7966 }
8067 }
8168
69+ // Check if user is staff for protected routes
8270 let userIsStaff = false ;
8371 if ( context . cookies . get ( internalAccessCookieName ) ?. value ) {
8472 try {
@@ -99,6 +87,23 @@ export const onRequest: MiddlewareHandler = async (context, next) => {
9987 }
10088 }
10189
90+ // ===== NOW RENDER THE PAGE =====
91+ const nextResponse = await next ( ) ;
92+
93+ // Add security headers to response
94+ const EXTRA_HEADERS = {
95+ "X-Content-Type-Options" : "nosniff" ,
96+ "Referrer-Policy" : "strict-origin-when-cross-origin" ,
97+ "Permissions-Policy" :
98+ "camera=(), microphone=(), geolocation=(), payment=()" ,
99+ "X-Frame-Options" : "DENY" ,
100+ "Strict-Transport-Security" : "max-age=31536000; includeSubDomains" ,
101+ } ;
102+
103+ for ( const [ key , value ] of Object . entries ( EXTRA_HEADERS ) ) {
104+ nextResponse . headers . set ( key , value ) ;
105+ }
106+
102107 const fullBackendUrl = path . join ( backendUrl , url . pathname ) + url . search ;
103108
104109 // skip as new pages are moved to astro
0 commit comments