useServerContext

useServerContext gives you access to the PageEvent received by the server.
tsx
const serverContext = useServerContext();
tsx
const serverContext = useServerContext();


Usage

useServerContext is a hook that gives you access to the PageEvent received by the server.

Accessing the request on the server

One common use case of this is to get the cookies. Cookies can be used to save user-preferences as session data. These preferences can be used to personalize the page on the server and the client identically.

tsx
import { parseCookie, useServerContext } from "solid-start";
import { isServer } from "solid-js/web";
 
function Component() {
const event = useServerContext();
const cookie = () => parseCookie(
isServer
? event.request.headers.get("cookie") ?? ""
: document.cookie
);
return <div>{JSON.stringify(cookie())}</div>;
}
tsx
import { parseCookie, useServerContext } from "solid-start";
import { isServer } from "solid-js/web";
 
function Component() {
const event = useServerContext();
const cookie = () => parseCookie(
isServer
? event.request.headers.get("cookie") ?? ""
: document.cookie
);
return <div>{JSON.stringify(cookie())}</div>;
}

Reference

useServerContext()

ts
function Component() {
const event = useServerContext();
return <div>{JSON.stringify(event)}</div>;
}
ts
function Component() {
const event = useServerContext();
return <div>{JSON.stringify(event)}</div>;
}

Returns the PageEvent received by the server. The properties of the PageEvent are:

  • request: The web standard Request object.
  • clientAddress: The IP address of the remote client.
  • locals: An object for storing local data that lives the life of the request, like user or authentication data.
  • fetch: internal fetch function that can make requests to our own API routes locally.
  • responseHeaders: The Headers object that will be sent to the client with the Response.
  • setStatusCode(code: number): A function to set the status code of the Response.
  • getStatusCode(): A function to get the status code of the Response.