Is there a way to have Rewrites or Proxy? #2399
-
This might be a dumb question, but I couldn't find any docs for it, so I might as well ask. My team is moving away from nextjs (pages) and moving to TSR (tanstack router with start/vinxi). The reason this is a blocker for us is that we need to have the API set cookies from the same domain as the UI (due to multiple envs, legacy auth issue and others). FWIW, i tried the vite server proxy, but it seems that tanstack router intercepts the request before vite proxy can (assumption). In our // nextjs.config.ts
{
rewrites() {
return [
{ source: "/api/avatar/:path*", destination: `${API_URL}/members/:path*/avatar` },
{ source: "/api/:path*", destination: `${API_URL}/:path*` },
];
},
} We played around a bit and have a very hacky solution which is very obnoxious. We do send headers and other through, but not in this example. // routes/api/$.ts
// ...
function constructUrl(splat: any) {
return `${getApiBaseUrl()}/${
Array.isArray(splat) ? splat.join("/") : typeof splat === "object" ? Object.values(splat).join("/") : splat
}`;
}
const createResponse = (data: any, headers: Headers, status: number) =>
new Response(JSON.stringify(data), { headers, status });
export const Route = createAPIFileRoute("/api/$")({
GET: async ({ params }) => {
const { _splat } = params;
const url = constructUrl(_splat);
const res = await api.get(url);
return createResponse(res.data, res.headers, res.status);
},
POST: async ({ params, request }) => {
const { _splat } = params;
const body = await request.json();
const url = constructUrl(_splat);
const res = await api.post(url, body);
return createResponse(res.data, res.headers, res.status);
},
}); |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 20 replies
-
as of v1.58.7, we have the following: TanStack Start now exposes the example: import { defineConfig } from '@tanstack/start/config'
export default defineConfig({
server: {
routeRules: {
"/proxy/example": { proxy: { to: "https://example.com"} },
}
},
}) |
Beta Was this translation helpful? Give feedback.
-
How to rewrite In nextjs, we are using below configuration: // next.config.ts
const nextConfig: NextConfig = {
async rewrites() {
return [
{
source: "/@:username/:path*",
destination: "/users/:username/:path*",
},
]
},
} |
Beta Was this translation helpful? Give feedback.
-
This works for me import {
createServerFileRoute,
getRequestIP,
proxyRequest,
} from "@tanstack/react-start/server";
const BACKEND_URL = import.meta.env.VITE_SERVER_URL || "http://localhost:8000";
export const ServerRoute = createServerFileRoute("/api/$").methods((api) => {
const handler = api.handler(async ({ request, params }) => {
const url = new URL(request.url);
const targetUrl = `${BACKEND_URL}/api/${params._splat ?? ""}${url.search}`;
const ip = getRequestIP({ xForwardedFor: true });
await proxyRequest(targetUrl, { headers: { "X-Forwarded-For": ip } });
return new Response();
});
return {
GET: handler,
POST: handler,
PUT: handler,
PATCH: handler,
DELETE: handler,
OPTIONS: handler,
HEAD: handler,
};
}); |
Beta Was this translation helpful? Give feedback.
-
This is what I am doing right now, using the API route. Sharing it in case anyone can get some inspiration. import { createFileRoute } from "@tanstack/react-router";
const API_HOST = "us.i.posthog.com" as const;
const ASSET_HOST = "us-assets.i.posthog.com" as const;
const posthogProxy = async ({ request }: { request: Request }) => {
const url = new URL(request.url);
const hostname = url.pathname.startsWith("/api/ingest/static/")
? ASSET_HOST
: API_HOST;
const newUrl = new URL(url);
newUrl.protocol = "https";
newUrl.hostname = hostname;
newUrl.port = "443";
newUrl.pathname = newUrl.pathname.replace(/^\/api\/ingest/, "");
const headers = new Headers(request.headers);
headers.set("host", hostname);
const response = await fetch(newUrl, {
method: request.method,
headers,
body: request.body,
});
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
};
export const Route = createFileRoute("/api/ingest/$")({
server: {
handlers: {
ALL: posthogProxy,
GET: posthogProxy,
POST: posthogProxy,
PUT: posthogProxy,
PATCH: posthogProxy,
DELETE: posthogProxy,
OPTIONS: posthogProxy,
HEAD: posthogProxy,
},
},
}); |
Beta Was this translation helpful? Give feedback.
as of v1.58.7, we have the following:
TanStack Start now exposes the
routeRules
config option from nitro: https://nitro.unjs.io/guide/routing#route-rulesexample: