Use Effect on the server
Run Effects with each request's session in server functions, actions and route handlers, sign in on the server, and render queries per request.
With server rendering, your server functions, actions and route handlers
run Effects too. There, the session is the encrypted cookie the server
keeps (Server sessions), and each
request has its own. This guide runs your Effects with that request's
session, so Auth.session, Auth.credentials and sessionBearer work on
the server as they do in the browser. sessionBearer sends the cookie's
access token, and saves a renewed one after a 401.
Each framework's adapter gives one request's session (RequestAuth), and
Auth.layer takes it. The rule that shapes this page: a request's session
belongs to that request, and so does everything that uses it.
Before you begin
- Follow your framework's guide, which creates the server engine and
registers the browser's
createMirrorAuthclient: TanStack Start, Next.js or React Router. - Follow steps 1, 2 and 6 of
Use Effect in the browser. The server's files
build on the
src/backend.ts,src/refresh.ts,src/api.tsandsrc/user.tsthey add. - Effect asks for TypeScript 5.9 or newer.
- To render queries with effetch-query in step 5, you need React 19: its React bindings don't support React 18. Compatibility lists every version.
1. Create the server engine
On the server, the session comes from createServerAuth, with the user
schema the app registers and the same refresh as the browser. Your
framework's guide creates serverAuth. Build it from userSchema and
refreshSession, as this src/server/auth.ts does:
import { } from "@monarcode/session-kit/server";
import { } from "../backend.js";
import { } from "../refresh.js";
declare const : string; // from the environment
export const = ({
: "app",
: ,
,
: ({ , }) => (, ),
});
/** One request's session, as your framework's adapter gives it. */
export type = <typeof .>;2. Run Effects per request
Build the session's layer and the API client per request, and keep one runtime for what belongs to no user:
import { } from "@monarcode/session-kit/effect";
import * as from "effect/Effect";
import * as from "effect/http/FetchHttpClient";
import * as from "effect/Layer";
import * as from "effect/ManagedRuntime";
import { type , } from "../api.js";
import type { } from "./auth.js";
/** Built once: what belongs to no user. */
const = .(.);
/** Built per request: its session, and the API client that uses it. */
export const = (: ) =>
.(.(.()));
/** Runs `effect` with the request's `session`. */
export function <, >(
: ,
: .<, , | >,
): <> {
return .(
.(, ()),
);
}The runtime has no Auth and no API client. So an Effect that needs them
doesn't compile until it goes through runRequest, and nothing a service
keeps outlives its request.
3. Call your API from a server function
Each framework's adapter gives the request's session in the server
function, action or handler. Pass it to runRequest with the Effect:
import { } from "../user.js";
import type { } from "./auth.js";
import { } from "./run.js";
// TanStack Start: startAuth(serverAuth). React Router:
// routerAuth(serverAuth)(context). Next.js, from
// nextSession(serverAuth, { cookies, redirect }): await session.writable()
// in a Server Function, or await session.readOnly() in a Server Component.
export const = (: ) =>
(, );A request's session explains each adapter.
4. Sign in on the server
Auth.signIn and Auth.updateUser take what the browser client's methods
take, so they aren't available on a request's session. Sign in with the
session's own signIn, which takes the tokens and the user, and update the
user with its own updateUser. Ask your backend with an Effect, then save
what it returns with the session's signIn:
import { } from "../user.js";
import type { } from "./auth.js";
import { } from "./run.js";
export async function (
: ,
: string,
: string,
) {
const { , , ... } = await (
,
(, ),
);
return .({ , , });
}5. Optional: Render queries on the server
To render a page with its data from effetch-query, make a query client per request, on the server, over that request's layer:
import { } from "@monarcode/effetch-query";
import * as from "effect/http/FetchHttpClient";
import * as from "effect/Layer";
import type { } from "./auth.js";
import { } from "./run.js";
export const = (: ) =>
.({
: ().(.(.)),
});Give it no memoMap: Things to know says why. Pass it to
QueryProvider as client while the page renders, and dispose of it after
the page is sent. For a server that answers with a streamed Response,
QueryClient.disposeAfter does that:
import { } from "@monarcode/effetch-query";
import type { } from "./auth.js";
import { } from "./query-client.js";
/** `render` gives `<QueryProvider client={queryClient}>` its tree. */
export async function (
: ,
: (: .) => <>,
): <> {
const = ();
try {
return .(, await ());
} catch () {
await .();
throw ;
}
}Each framework has its own place for the client and its disposal, which effetch-query's Frameworks section shows:
- TanStack Start: make the client in
getRouter, andconnectQueryClientdisposes it when the request ends. - Next.js: make it with React's
cache(), and dispose of it inafter(). - React Router: make it in middleware, and wrap the response in
QueryClient.disposeAfter, asrespondWithQueriesdoes.
A page's render can't always save a renewed cookie: a Next.js Server Component never can, and TanStack Start loses a cookie set after the page starts streaming. So refresh before the page renders, in middleware or Proxy, as each framework guide does. In TanStack Start, a prefetch that runs before the page starts streaming can also save a renewed cookie. In the browser, the cache is the owned one from Give each account its own cache, over the mirror client.
Things to know
- One registration. An app with server rendering registers its mirror
client, and that registration types
Authon the server too.Auth.layertakes a request's session whose user is the registered one. In the browser, buildAuth.layer(mirror)where the mirror is created. There,Auth.signInneeds the mirror'ssignInoption, andAuth.updateUserisn't available, since the user comes from the server.sessionBearerin the browser needsclientCredentials: trueincreateServerAuth, or the mirror'scredentialsoption (The access token in the browser). - Keep server modules free of the browser client. In this guide, the
server's files import only
src/backend.ts,src/refresh.ts,src/api.tsandsrc/user.ts, which create no Session kit client. Keep it that way in your app. A module the server imports, such as the one that definesApiClientLiveor the user schema, mustn't also create a browser client or its layer, or the server loads it too. - Name the services in
runRequest's signature, assrc/server/run.tsdoes, rather than inferring them fromrequestLayer. With a mirror registered, the registration depends on the server functions the mirror calls, which callrunRequest, and TypeScript reports a circular type. For the same reason, the server functions the mirror is made from, such as itsrevalidateandsignIn, read the request's session directly, notAuth.session. - Keep a request's layer off a shared
memoMap, such as the runtime's or one passed toQueryClient.make. Layers are shared by identity there, so overlapping requests can get one build. A service that keepsAuthwhen it's built would then serve one request's session to another. - Requests that can't set cookies, such as a Next.js Server
Component's.
Auth.sessionreturns the cookie's session as it is.Auth.credentialsandsessionBearerfail withREFRESH_FAILEDafter the access token has expired, or after a 401, since nothing new can be saved. Refresh first, in middleware or Proxy, as the framework guides do.Auth.signOutdies there withINVALID_OPTIONS, so sign out in an action or route handler. A request's session lists which requests these are. - Only
Auth's Effects. A request's session isn't your browser client, so don't reach for client methods throughAuth.usethere. Auth.layerbinds a session fromstartAuthto the request that's current when it's called, so call it per request, asrequestLayerdoes. Outside a request, it throwsINVALID_OPTIONS.
Next steps
- Server sessions: how the server keeps the session in a cookie, and refreshes it.
- Effect and effetch: what
Authcovers, and howsessionBearerdiffers fromcreateAuthFetch. ./effectreference:Auth.layerand every other export.