Skip to content

hook.server.ts does not work for a preflight request #8963

@taishi55

Description

@taishi55

Describe the bug

Error message on client side: Access to fetch at 'https://myapp-vercel.app/api/search' from origin 'https://chat.openai.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Reproduction

hooks.server.ts (Deployed to Vercel.)

import type { Handle } from '@sveltejs/kit';

export const handle: Handle = async ({ event, resolve }) => {
	const response = await resolve(event);
	if (event.url.pathname.includes('/api')) {
		// https://chat.openai.com
		response.headers.set('Access-Control-Allow-Origin', 'https://example.com');
		response.headers.set('Access-Control-Allow-Methods', 'GET,OPTIONS,POST');
		response.headers.set('Access-Control-Max-Age', '86400');
	}
	return response;
};

+server.ts (Deployed to Vercel.)

export const POST: RequestHandler = async ({ request }) => {
	const { query, time, instruction } = await request.json();
	try {
	const data: string = await getTranscript(query);
	return new Response(data, { status: 200 });
	} catch {
	return new Response("" { status: 500 });
	}
}

Fetching from the origin (https://example.com) on client side:

const submit = async () => {
		const headers = new Headers({
			Origin: 'https://example.com',
			'content-type': 'application/json'
		});
		try {
			const response = await fetch('https://myapp.com/api/search', {
				method: 'POST',
				body: JSON.stringify({
					query,
					time,
					instruction
				}),
				headers
			});

			result = await response.text();
		} catch (error) {
			// showErrorMessage(error);
			console.log(error);
		}
	};

Logs

I've been searching this issue a lot. There are some people who experience the same isssue.
https://www.reddit.com/r/sveltejs/comments/u4wepc/solving_cors_problems_when_using_sveltekitvercel/

https://discord.com/channels/457912077277855764/1023340103071965194/threads/1051823361933705216

System Info

System:
    OS: macOS 12.4
    CPU: (8) arm64 Apple M1
    Memory: 103.13 MB / 8.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.15.0 - /usr/local/bin/node
    npm: 8.19.2 - /usr/local/bin/npm
  Browsers:
    Brave Browser: 109.1.47.186
    Safari: 15.5
  npmPackages:
    @sveltejs/adapter-auto: ^2.0.0 => 2.0.0 
    @sveltejs/kit: ^1.5.0 => 1.5.0 
    svelte: ^3.54.0 => 3.55.1 
    vite: ^4.0.0 => 4.1.1

Severity

annoyance

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions