Worker for origin routing between two hosts (NextJS apps)

I'm looking to setup a worker which essentially setting up an origin rule to redirect users to another hosted domain / NextJS app. For example, when they go to the origin path, they are then re-routed to the target path. Origin: https://www-staging.host.com/login Target: https://app-staging.host.com/login (for purpose of this post i've redacted the host) When I go to the target, the page is loading fine. However, when doing it via the origin route, the page is breaking with 404 not found. For example: https://www-staging.host.com/_next/static/chunks/874-facbfc8a4bd659c3.js%20net::ERR_ABORTED%20404%20(Not%20Found) This is my current worker. Has anyone else had success with this type of issue / workers for nextjs apps?
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);

const APP_PREFIXES = ["/login"];
const toApp = APP_PREFIXES.some(
p => url.pathname === p || url.pathname.startsWith(p + "/")
);

// Choose target origin
const targetBase = toApp
? "https://app-staging.host.com"
: "https://www-staging.host.com";

const upstream = new URL(url.pathname + url.search, targetBase);

const headers = new Headers(request.headers);
headers.set("Host", new URL(targetBase).host);

const init = {
method: request.method,
headers,
body: ["GET", "HEAD"].includes(request.method)
? undefined
: await request.arrayBuffer(),
redirect: "follow",
};

if (request.headers.get("Cookie")) {
init.cf = { cacheTtl: 0, cacheEverything: false };
}

return fetch(upstream, init);
}
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);

const APP_PREFIXES = ["/login"];
const toApp = APP_PREFIXES.some(
p => url.pathname === p || url.pathname.startsWith(p + "/")
);

// Choose target origin
const targetBase = toApp
? "https://app-staging.host.com"
: "https://www-staging.host.com";

const upstream = new URL(url.pathname + url.search, targetBase);

const headers = new Headers(request.headers);
headers.set("Host", new URL(targetBase).host);

const init = {
method: request.method,
headers,
body: ["GET", "HEAD"].includes(request.method)
? undefined
: await request.arrayBuffer(),
redirect: "follow",
};

if (request.headers.get("Cookie")) {
init.cf = { cacheTtl: 0, cacheEverything: false };
}

return fetch(upstream, init);
}
Thank you
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?