T
TanStack6mo ago
optimistic-gold

Grabbing window.location.origin in ssr best ways?

this might be a dumb question but my page is using ssr to render but i need to pass window.location.origin but that wouldn't work from the server, right? any workarounds people might know? Or does it make sense to just store my website's url in an env var?
export const Route = createFileRoute("/_auth/$pathname")({
component: RouteComponent,
});

function RouteComponent() {
const { pathname } = Route.useParams();
console.log(pathname);
console.log(window.location.origin);
return (
<>
<AuthCard
pathname={pathname}
socialLayout="auto"
redirectTo="/profile"
callbackURL={window.location.origin}
classNames={{ title: "text-center", description: "text-center" }}
/>
</>
);
}
export const Route = createFileRoute("/_auth/$pathname")({
component: RouteComponent,
});

function RouteComponent() {
const { pathname } = Route.useParams();
console.log(pathname);
console.log(window.location.origin);
return (
<>
<AuthCard
pathname={pathname}
socialLayout="auto"
redirectTo="/profile"
callbackURL={window.location.origin}
classNames={{ title: "text-center", description: "text-center" }}
/>
</>
);
}
I did with this workaround using a serverfn, not sure if it's the best way
import { createServerFn } from "@tanstack/react-start";
import { getHeaders } from "@tanstack/react-start/server";

/**
* Fetch the active subscriptions for the currently logged in user
*/
export const getHost = createServerFn({ method: "GET" }).handler(async () => {
const headers = getHeaders();
const host = headers.host || undefined;
const protocol =
process.env.NODE_ENV === "production" ? "https://" : "http://";
return host ? `${protocol}${host}` : undefined;
});

//component
export const Route = createFileRoute("/_auth/$pathname")({
component: RouteComponent,
loader: async () => getHost(),
});
...
import { createServerFn } from "@tanstack/react-start";
import { getHeaders } from "@tanstack/react-start/server";

/**
* Fetch the active subscriptions for the currently logged in user
*/
export const getHost = createServerFn({ method: "GET" }).handler(async () => {
const headers = getHeaders();
const host = headers.host || undefined;
const protocol =
process.env.NODE_ENV === "production" ? "https://" : "http://";
return host ? `${protocol}${host}` : undefined;
});

//component
export const Route = createFileRoute("/_auth/$pathname")({
component: RouteComponent,
loader: async () => getHost(),
});
...
2 Replies
correct-apricot
correct-apricot6mo ago
Or does it make sense to just store my website's url in an env var
absolutely!
optimistic-gold
optimistic-goldOP6mo ago
Thanks!

Did you find this page helpful?