How do I get the host or full request url inside a "use server" function?

For example, maybe I have this:
// src/routes/posts/[id]/index.tsx
import { ErrorBoundary } from "solid-js";
import { query, createAsync, type RouteDefinition } from "@solidjs/router";

const getPost = query(async (id: string) => {
"use server";
const post = await fetch(`https://my-api.com/posts/${id}`);
return await post.json();
}, "post");

export const route = {
preload: ({ params }) => getPost(params.id),
} satisfies RouteDefinition;

export default function Page() {
const postId = 1;
const post = createAsync(() => getPost(postId));
return (
<div>
<ErrorBoundary fallback={<div>Something went wrong!</div>}>
<h1>{post().title}</h1>
</ErrorBoundary>
</div>
);
}
// src/routes/posts/[id]/index.tsx
import { ErrorBoundary } from "solid-js";
import { query, createAsync, type RouteDefinition } from "@solidjs/router";

const getPost = query(async (id: string) => {
"use server";
const post = await fetch(`https://my-api.com/posts/${id}`);
return await post.json();
}, "post");

export const route = {
preload: ({ params }) => getPost(params.id),
} satisfies RouteDefinition;

export default function Page() {
const postId = 1;
const post = createAsync(() => getPost(postId));
return (
<div>
<ErrorBoundary fallback={<div>Something went wrong!</div>}>
<h1>{post().title}</h1>
</ErrorBoundary>
</div>
);
}
the issue is at
const post = await fetch(`https://my-api.com/posts/${id}`);
const post = await fetch(`https://my-api.com/posts/${id}`);
The https://my-api.com part needs to change according to the current host of the request (eg. development would be localhost, staging would be somewhere else etc.) How can I access that within the getPost function? window is not available so I can't do window.location.hostname It would also be helpful to be able to access the full request url in there
2 Replies
Madaxen86
Madaxen862mo ago
Probably best is to use environment variable for this. But there is also getReuqestEvent() https://docs.solidjs.com/reference/server-utilities/get-request-event#getrequestevent
getRequestEvent - Solid Docs
Documentation for SolidJS, the signals-powered UI framework
chanon_s
chanon_sOP2mo ago
Thank you! That works

Did you find this page helpful?