Can't set headers in hooks.server handle function in vercel #12146

Hello, I was trying to add security headers to my sveltekit web app:

const handleSecurityHeaders: Handle = async ({ event, resolve }) => {
    const response = await resolve(event)

    response.headers.set('X-Frame-Options', 'DENY')
    response.headers.set('X-Content-Type-Options', 'nosniff')
    response.headers.set('Referrer-Policy', 'no-referrer-when-downgrade')
    response.headers.set('Permissions-Policy', 'camera=(), microphone=(), geolocation=()')
    response.headers.set('Access-Control-Allow-Origin', config.site_url || '*')

    return response
}

the headers appear when I’m in dev mode but when I deploy it to Vercel I can’t see them until I add them to vercel.json

{
	"$schema": "https://openapi.vercel.sh/vercel.json",
	"headers": [
		{
			"source": "/(.*)",
			"headers": [
				{ "key": "Access-Control-Allow-Origin", "value": "https://islamzaoui.top" },
				{ "key": "X-Frame-Options", "value": "SAMEORIGIN" },
				{ "key": "X-Content-Type-Options", "value": "nosniff" },
				{ "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" },
				{ "key": "Permissions-Policy", "value": "geolocation=(), camera=(), microphone=()" }
			]
		}
	]
}

any suggestions?

Hi, @islamzaoui! Welcome to the Vercel Community.

You can use both vercel.json and SvelteKit hooks.

I’d suggest to continue using the vercel.json file for setting critical security headers. This ensures they’re set at the Edge Network level and are present in all responses.

You can also use SvelteKit’s hooks for headers that need to be set dynamically or based on the request/response.

Sharing some relevant documentation that may be helpful.

Let us know how you get on!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.