Skip to content

cloudflare-adapter usage with Cloudflare Pages functions #2840

@boojum

Description

@boojum

Describe the bug

I'm trying to add a CORS proxy function to a SvelteKit app running on Cloudflare Pages (deployed here, repo here). Source of the (trivial) proxy function lives at function/corsproxy/[[any]].js and looks as follow:

const API_URL = 'https://itunes.apple.com/';

const corsHeaders = {
	'Access-Control-Allow-Origin': '*',
	'Access-Control-Allow-Methods': 'GET,HEAD,POST,OPTIONS',
	'Access-Control-Max-Age': '86400'
};

export async function onRequest(context) {
	// Contents of context object
	let {
		request, // same as existing Worker API
		env, // same as existing Worker API
		params, // if filename includes [id] or [[path]]
		waitUntil, // same as ctx.waitUntil in existing Worker API
		next, // used for middleware or to fetch assets
		data // arbitrary space for passing data between middlewares
	} = context;

	const url = new URL(request.url);

	request = new Request(API_URL, request);
	request.headers.set('Origin', new URL(API_URL).origin);
	let response = await fetch(request);

	// Recreate the response so we can modify the headers
	response = new Response(response.body, response);

	// Set CORS headers
	response.headers.set('Access-Control-Allow-Origin', url.origin);

	// Append to/Add Vary header so browser will cache response correctly
	response.headers.append('Vary', 'Origin');

	return response;
}

The "bare" app, without function/corsproxy/[[any]].js, renders just fine although it produces the "Access-Control-Allow-Origin" CORS error. With the proxy function all requests to the app produce 404, even request for the static assets.

Reproduction

  1. Create a Gitlab repo, initialise it with code from this repo.
  2. Create a Cloudflare Pages project with the repo from 1. For the project settings use:
    • Build command: npm run build
    • Build output directory: .svelte-kit/cloudflare
    • correct node version is set via .node-version file
  3. Deploy & visit the app.
  4. Observe 404 errors.

Logs

No response

System Info

System:
    OS: Linux 5.13 Ubuntu 21.10 21.10 (Impish Indri)
    CPU: (4) x64 Intel(R) Pentium(R) CPU N4200 @ 1.10GHz
    Memory: 341.84 MB / 3.67 GB
    Container: Yes
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 16.13.0 - /usr/bin/node
    npm: 8.1.0 - /usr/bin/npm
  Browsers:
    Chrome: 96.0.4664.45
    Firefox: 94.0.1
  npmPackages:
    @sveltejs/adapter-cloudflare: ^1.0.0-next.2 => 1.0.0-next.2 
    @sveltejs/kit: next => 1.0.0-next.196 
    svelte: ^3.42.6 => 3.44.1

Severity

blocking all usage of SvelteKit

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions