Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
55 lines (49 loc) · 1.85 KB
/
Copy pathserver.ts
File metadata and controls
55 lines (49 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { createRequestHandler, RouterContextProvider } from "react-router";
import * as serverBuild from "virtual:react-router/server-build";
import { envContext } from "~/lib/env";
/**
* Export a fetch handler in module format for Oxygen / mini-oxygen.
*/
export default {
async fetch(
rawRequest: Request,
env: Env,
executionContext: ExecutionContext,
): Promise<Response> {
try {
const request = toPublicRequest(rawRequest);
const method = request.method;
if ((method === "GET" || method === "HEAD") && request.body) {
return new Response(`${method} requests cannot have a body`, { status: 400 });
}
const url = new URL(request.url);
if (url.pathname.includes("//")) {
return new Response(null, {
status: 301,
headers: { location: url.pathname.replace(/[/]+/g, "/") },
});
}
const routerContext = new RouterContextProvider();
routerContext.cache = await caches.open("hydrogen-v1");
routerContext.set(envContext, env);
routerContext.env = env;
routerContext.waitUntil = executionContext.waitUntil.bind(executionContext);
const handleRequest = createRequestHandler(serverBuild, process.env.NODE_ENV);
return handleRequest(request, routerContext as never);
} catch (error) {
console.error(error);
return new Response("An unexpected error occurred", { status: 500 });
}
},
};
// Behind a proxy that terminates TLS, such as a tunnel, the worker sees `http:`
// with `x-forwarded-proto: https`. Customer Account OAuth needs the public
// `https:` origin.
function toPublicRequest(request: Request): Request {
const url = new URL(request.url);
if (url.protocol !== "http:" || request.headers.get("x-forwarded-proto") !== "https") {
return request;
}
url.protocol = "https:";
return new Request(url, request);
}