Server-rendered app
In the wizard: No API that Otoko Identity calls · Web app, server code at sign-in
A website whose pages your server renders, such as Express, Next.js or FastAPI, that needs people signed in and nothing more. Your server does the sign-in and keeps a client secret, which never reaches the browser. Otoko Identity (OI) calls nothing on your side: it runs sign-up, forgot password and invitations on its own pages, and you manage roles in OI's console.
What you'll build
/auth/login, which sends people to OI's sign-in page, where they can also Register and use Forgot password./auth/callback, where OI sends them back and your server swaps the code for tokens with its client secret.- A session the browser can't read, and an
/accountpage only a signed-in person sees, with their name, email and roles. /auth/logout, which signs people out of your app and of OI.
Trying it with Otoko Identity on your own machine?
The examples use https://identity.example.com for Otoko Identity. With OI running locally in Docker, its address is http://localhost:8001 and the console is at http://localhost:3100/admin. Your app runs on localhost as usual.
With a coding agent
To have Claude Code, Cursor or another coding agent do these steps in your project, paste it this prompt. Check what it writes against the steps below.
Paste this into your coding agent, in your web app's project. It tells you what to register on the console, then writes sign-in, the callback, a session the browser can't read and sign-out on your server, with its client secret.
Show the full prompt
Connect this server-rendered app's sign-in to Otoko Identity
You are connecting the sign-in of the web app you're working in to Otoko Identity (OI), a standard OpenID Connect provider. The app's own server renders its pages and signs people in with a client secret, which never reaches the browser. It needs people signed in and nothing more: OI calls nothing on its side. Work through the steps below in order, and stop where a step says to wait for the person.
Scope
/auth/login, which sends people to OI;/auth/callback, where the server swaps the code for tokens; a session the browser can't read; an/accountpage only a signed-in person sees, with their name, email and roles; and/auth/logout, which signs people out of the app and of OI.- OI runs sign-up, forgot password and invitations on its own pages, and roles are managed on OI's console. Don't build them.
- Change nothing unrelated to signing in.
Rules
- The client secret and
SESSION_SECRETlive only in an env file that git ignores.- Never open, print or paste the whole env file, and never ask for a secret in the chat. To check a setting is there, look for its name only (for example
grep -c '^IDENTITY_CLIENT_SECRET=' .env). - Never put a secret in browser code, a log line or a commit.
- Never open, print or paste the whole env file, and never ask for a secret in the chat. To check a setting is there, look for its name only (for example
- Use a maintained OpenID Connect library: openid-client on a Node server, Authlib in Python, or the established one for the project's stack. Never write the flow by hand.
- Never let the page's JavaScript see the tokens: the browser gets only the session cookie.
- Use https everywhere outside a local machine.
1. Look at the project
- Find its framework (Express, Next.js with the App Router, and FastAPI are the worked examples; NestJS, Fastify, Django, Flask or Rails take the same steps), how it runs, its address and port, where its routes live, how it keeps sessions, and any sign-in it already has.
- Confirm with the person that its server renders the pages and that OI needn't call it. If it should also hear from OI (who may sign in, ended sessions, new accounts) or keep its own users, stop and send them to the prompt on https://identity-docs.otoko.com/quickstarts/server-rendered-app-with-api. If it's a single-page app, send them to https://identity-docs.otoko.com/quickstarts/browser-app.
2. Tell the person what to register, then wait
The app is registered on OI's console; you can't do this part.
- Name the env file the settings go in:
.env, or.env.localfor Next.js. Check that git ignores it before anything is pasted, and add it to.gitignoreif not. - Tell the person to open https://identity.otoko.com/admin/apps/new and:
- Name your app: type the App name. To Does your app have an API that Otoko Identity calls? answer No.
- How people sign in: choose Web app, and to Does your app run server code when someone signs in? leave Yes. Type the App address, such as
http://localhost:3000. Open Advanced and change the Sign-in return address to the address plus/auth/callback. Leave the Sign-out return address as the front page. - Email: leave Send this app's emails through Otoko Identity's mail server ticked, with an optional Reply-to address. Only for an app with its own mail server, untick it, type the From address, and fill in the Mail server section that appears: host, port, encryption, username and password. The person types the password there themselves; never ask for it in the chat.
- Choose Create, then on Connect your app the Frontend section's Copy all, and paste it into the env file you named. It includes the Client secret, for the server only, sent with HTTP Basic authentication at the token endpoint. The client secret and API key are shown only now. This app doesn't use the Server section's API key.
- Turn on sign-up: a new client starts with it off. Open Apps, the app, the Clients tab and the client, turn on Allow sign-up, and choose Save client.
- Add a role: on the app's Users & roles tab, set Roles managed by to Admin console, choose Add role, type
member, and choose Save changes.
- Ask them to tell you when it's done, and wait. Then check the paste by names only.
3. Settings
The code reads these, from the env file:
IDENTITY_ISSUER,IDENTITY_CLIENT_ID,IDENTITY_CLIENT_SECRET,IDENTITY_REDIRECT_URIandIDENTITY_SCOPES, from the Frontend section's Copy all. AddrolestoIDENTITY_SCOPES(such asopenid profile email roles), editing only that line, so the app can read roles.APP_URL, where the app runs, such ashttp://localhost:3000, andSESSION_SECRET, a long random string of at least 32 characters. Both are the app's own: add them, generating the secret into the file without printing it.- For FastAPI with a local OI on plain http only,
AUTHLIB_INSECURE_TRANSPORT=1. Never with https.
Add an .env.example with the same names and placeholder values.
4. Install
- Express:
express express-session openid-client, withtypescript tsx @types/express @types/express-session @types/nodeas dev dependencies. The examples are ES modules ("type": "module"). - Next.js:
openid-client iron-session. - FastAPI:
fastapi,uvicorn[standard],authlib,httpx,itsdangerousandpython-dotenv.
5. The code
The connection to OI, read once, such as src/oidc.ts, lib/oidc.ts or app/oidc.py: discovery from IDENTITY_ISSUER (<issuer>/.well-known/openid-configuration), IDENTITY_CLIENT_ID, and IDENTITY_CLIENT_SECRET sent as HTTP Basic, the console's default. With openid-client, allow plain http only when the issuer is http:. If discovery fails, ask again next time rather than keep the failure.
The session:
- Express: express-session, kept on the server, with an httpOnly, SameSite=Lax cookie,
securewhenAPP_URLis https, andproxy: true. The memory store suits development only. - Next.js: an iron-session cookie sealed with
SESSION_SECRET, httpOnly, SameSite=Lax,securewhenAPP_URLis https. - FastAPI: Starlette's
SessionMiddlewarewithSESSION_SECRET, holding only a random id for the signed-in person, who is kept on the server. - It holds the sign-in in progress (PKCE verifier, state and nonce), then the person: access token, ID token, when the access token expires, name, email and roles.
currentUser()treats an expired access token as signed out.
GET /auth/login: keeps a new PKCE verifier, state and nonce in the session, and redirects to OI's authorization endpoint with IDENTITY_REDIRECT_URI, IDENTITY_SCOPES, the S256 code challenge, the state and the nonce.
GET /auth/callback:
- With no sign-in in progress, redirect to
/auth/login. - Swap the code with the PKCE verifier and the client secret; the library checks the state, the nonce and the ID token. Build the callback URL on
APP_URL, not on the request's own host. - Fetch userinfo with the access token for the name, email and roles. OI's ID token holds only who signed in and how.
- Start a new session (regenerate its id), store the person, and redirect to
/account. - On an error, answer 400 with the reason, HTML-escaped, and a link back to
/auth/login.
POST /auth/logout: a POST from the app's own pages only: refuse with 403 when Sec-Fetch-Site is present and not same-origin, or, without it, when Origin is present and isn't APP_URL's origin. Read the ID token, destroy the session, and redirect (303) to OI's end-session endpoint with id_token_hint and post_logout_redirect_uri set to APP_URL plus /. Without the ID token, OI won't return the person to the app.
The pages:
/: a Sign in link to/auth/login, or, signed in, the email and a link to/account./account, behind a check that sends anyone not signed in to/auth/login:Hello,and the name (or email), the email,Roles:and the roles (ornone), and a form that POSTs to/auth/logout. Escape everything you put in HTML. In Next.js, keepexport const instant = falseon pages that read the session.
6. Check it works
Run the app (npm run dev, or uvicorn app.main:app --port 3000 --env-file .env) and open http://localhost:3000. You can't sign in for the person, so ask them to:
- Choose Sign in, then Register on OI's page, and type the code OI emails. They land on
/account, with their name and email. - In the console, give themselves the
memberrole, then sign out and in again./accountsays Roles: member. - In the browser's developer tools, see that the session cookie is HttpOnly.
- Choose Sign out, then Sign in again. OI asks for their email: its own session ended too.
If OI answers invalid_redirect_uri, IDENTITY_REDIRECT_URI and the client's Valid redirect URIs differ. If the callback fails with invalid_client, the secret is wrong or rotated. For other errors, read https://identity-docs.otoko.com/troubleshooting.
Finish with a short report: the files you changed, the routes and pages you added, the settings the code reads (by name), and anything the person still has to do, such as a real session store and the live addresses before going live.
More detail
- https://identity-docs.otoko.com/quickstarts/server-rendered-app: this setup, step by step, with Express, Next.js and FastAPI code.
- https://identity-docs.otoko.com/api-reference/openid-connect: the flow, endpoints and scopes.
- https://identity-docs.otoko.com/api-reference/errors: every error code.
Register the app
-
In the console, open Connect an app.
-
Name your app: type the App name. To Does your app have an API that Otoko Identity calls? answer No.
-
How people sign in: choose Web app, and to Does your app run server code when someone signs in? leave Yes. Type the App address, such as
http://localhost:3000. Open Advanced and change the Sign-in return address to the address plus/auth/callback, such ashttp://localhost:3000/auth/callback. Leave the Sign-out return address as the front page. -
Email:
Otoko Identity emails sign-up codes, forgot-password codes and invitations. Leave Send this app's emails through Otoko Identity's mail server ticked, and the app needs no mail server of its own; a Reply-to address is optional. Only if your app has its own mail server, untick it, type the From address OI sends from, and fill in the Mail server section that appears: host, port, encryption, username and password, the last two together, and its timeouts. It's saved when the app is made, and the last step offers Send test email.
-
Choose Create. On Connect your app, choose the Frontend section's Copy all: it includes the Client secret, sent with HTTP Basic authentication at the token endpoint. The client secret and API key are shown only now. This app doesn't use the Server section's API key.
-
Turn on sign-up. A new client starts with it off, and until it's on, OI's sign-in page shows no Register link. Open Apps, your app, the Clients tab, and your client. Turn on Allow sign-up, then choose Save client. (The app's own Sign-up allowed and Forgot password, under Login on its Overview tab, are on for a new app.)
-
Add a role. On the app's Users & roles tab, set Roles managed by to Admin console (an app with a backend starts on Application backend), choose Add role, type
member, and choose Save changes. Once someone has signed up, give them the role with the pencil button in their Roles column in the users list. Your app asks for therolesscope to read them.
Settings
The IDENTITY_ values come from the Frontend section's Copy all, with roles added to the scopes. APP_URL and SESSION_SECRET are your own: make the secret a long random string. The file holds secrets, so keep it out of git.
Copy .env.example to .env.
# Copy to .env. The IDENTITY_ values come from Connect an app's Frontend section (its Copy all).
# This file holds secrets: keep it out of git.
IDENTITY_ISSUER=https://identity.example.com
IDENTITY_CLIENT_ID=your-client-id
IDENTITY_CLIENT_SECRET=the-client-secret-shown-once
IDENTITY_REDIRECT_URI=http://localhost:3000/auth/callback
IDENTITY_SCOPES=openid profile email roles
# Your own: where the app runs, and a long random string that signs the session cookie.
APP_URL=http://localhost:3000
SESSION_SECRET=a-long-random-string-of-at-least-32-charactersCopy .env.example to .env.local, which Next.js reads on the server only.
# Copy to .env.local. The IDENTITY_ values come from Connect an app's Frontend section (its Copy all).
# This file holds secrets: keep it out of git.
IDENTITY_ISSUER=https://identity.example.com
IDENTITY_CLIENT_ID=your-client-id
IDENTITY_CLIENT_SECRET=the-client-secret-shown-once
IDENTITY_REDIRECT_URI=http://localhost:3000/auth/callback
IDENTITY_SCOPES=openid profile email roles
# Your own: where the app runs, and a long random string that signs the session cookie.
APP_URL=http://localhost:3000
SESSION_SECRET=a-long-random-string-of-at-least-32-charactersCopy .env.example to .env. With OI on plain http on your own machine, add AUTHLIB_INSECURE_TRANSPORT=1, as Authlib refuses http otherwise. Never set it with https.
# Copy to .env. The IDENTITY_ values come from Connect an app's Frontend section (its Copy all).
# This file holds secrets: keep it out of git.
IDENTITY_ISSUER=https://identity.example.com
IDENTITY_CLIENT_ID=your-client-id
IDENTITY_CLIENT_SECRET=the-client-secret-shown-once
IDENTITY_REDIRECT_URI=http://localhost:3000/auth/callback
IDENTITY_SCOPES=openid profile email roles
# Your own: where the app runs, and a long random string that signs the session cookie.
APP_URL=http://localhost:3000
SESSION_SECRET=a-long-random-string-of-at-least-32-characters
# Only for a local OI on plain http (Authlib refuses http otherwise). Leave it out with https.
# AUTHLIB_INSECURE_TRANSPORT=1Install
A new app. For an app you already have, skip the first two lines: the third sets type=module, which the examples' imports need, so check nothing of yours still uses require.
mkdir my-app && cd my-app
npm init -y
npm pkg set type=module scripts.dev="tsx watch --env-file=.env src/server.ts" scripts.typecheck="tsc --noEmit"npm install express express-session openid-client
npm install -D typescript tsx @types/express @types/express-session @types/nodeA new app (skip the first two lines for an app you already have):
npx create-next-app@latest my-app --ts --app --eslint --yes --no-src-dir --import-alias "@/*"
cd my-app
npm install openid-client iron-sessionA new app, with Python 3.10 or later. First save this as requirements.txt:
fastapi
uvicorn[standard]
authlib
httpx
itsdangerous
python-dotenvThen:
python -m venv .venv
# Windows: .venv\Scripts\activate macOS and Linux: source .venv/bin/activate
pip install -r requirements.txtAdd the code
Where these files go
src/oidc.ts: the connection to OI, read once.src/session.ts: the session, kept on the server, with what it holds.src/routes/auth.ts:/auth/login,/auth/callbackand/auth/logout.src/server.ts: the app, the front page, and/accountbehindrequireUser.tsconfig.json: fornpm run typecheck.tsxruns the code without a build step.
import * as client from 'openid-client';
let config: Promise<client.Configuration> | undefined;
/**
* Otoko Identity, read once from its discovery document (<issuer>/.well-known/openid-configuration).
* The client secret proves to OI that this server is the app.
*/
export function getOidcConfig(): Promise<client.Configuration> {
const issuer = new URL(process.env.IDENTITY_ISSUER!);
config ??= client
.discovery(
issuer,
process.env.IDENTITY_CLIENT_ID!,
undefined,
client.ClientSecretBasic(process.env.IDENTITY_CLIENT_SECRET!),
// Only for a local OI on plain http. Leave it out with https.
issuer.protocol === 'http:' ? { execute: [client.allowInsecureRequests] } : undefined,
)
.catch((error: unknown) => {
config = undefined; // ask again next time, rather than keep the failure
throw error;
});
return config;
}Where these files go
lib/oidc.ts: the connection to OI, read once.lib/session.ts: the session, as a sealed cookie, andcurrentUser().app/auth/login/route.ts,app/auth/callback/route.tsandapp/auth/logout/route.ts: the three routes.app/page.tsxandapp/account/page.tsx: the front page, and a page only a signed-in person sees.app/page.tsxreplaces the starter's.
import * as client from 'openid-client';
let config: Promise<client.Configuration> | undefined;
/**
* Otoko Identity, read once from its discovery document (<issuer>/.well-known/openid-configuration).
* The client secret proves to OI that this server is the app.
*/
export function getOidcConfig(): Promise<client.Configuration> {
const issuer = new URL(process.env.IDENTITY_ISSUER!);
config ??= client
.discovery(
issuer,
process.env.IDENTITY_CLIENT_ID!,
undefined,
client.ClientSecretBasic(process.env.IDENTITY_CLIENT_SECRET!),
// Only for a local OI on plain http. Leave it out with https.
issuer.protocol === 'http:' ? { execute: [client.allowInsecureRequests] } : undefined,
)
.catch((error: unknown) => {
config = undefined; // ask again next time, rather than keep the failure
throw error;
});
return config;
}Where these files go
app/oidc.py: the connection to OI, through Authlib.app/sessions.py: the signed-in people, kept on the server.app/main.py: the app, the three/authroutes, the front page and/account.
"""Otoko Identity, through Authlib. It reads OI's discovery document, and signs in with PKCE, a state and a nonce."""
import os
from authlib.integrations.starlette_client import OAuth
oauth = OAuth()
oauth.register(
name="identity",
server_metadata_url=f"{os.environ['IDENTITY_ISSUER']}/.well-known/openid-configuration",
client_id=os.environ["IDENTITY_CLIENT_ID"],
client_secret=os.environ["IDENTITY_CLIENT_SECRET"], # sent as HTTP Basic, the console's default
client_kwargs={"scope": os.environ["IDENTITY_SCOPES"], "code_challenge_method": "S256"},
)Using something else?
The steps are the same in any server framework: a login route, a callback route that swaps the code with the client secret, a session the browser can't read, and a logout route.
| Framework | Connection to OI | Session | Routes |
|---|---|---|---|
| NestJS | src/, with openid-client | express-session, set up in src/ | an AuthController in src/ |
| Fastify | src/, with openid-client | @fastify/ | a plugin in src/ |
| Django | yourapp/, with Authlib's Django client | Django's own sessions | yourapp/ and yourapp/ |
| Flask | app/, with Authlib's Flask client | Flask's session, plus a server-side store | app/, a blueprint |
| Rails | config/, with omniauth_openid_connect | Rails' own sessions | app/ |
Run and check
npm run devOpen http://localhost:3000.
npm run devOpen http://localhost:3000.
uvicorn app.main:app --port 3000 --env-file .envOpen http://localhost:3000.
- Choose Sign in. OI's sign-in page opens.
- Choose Register, fill in the form, and type the code OI emails you. You land on
/account, with your name and email. - In the console, give yourself the
memberrole, then sign out and in again./accountsays Roles: member. - In the browser's developer tools, the session cookie is HttpOnly: the page's JavaScript can't read it. With Express and FastAPI it holds only a session ID; with Next.js it holds the session sealed with
SESSION_SECRET, which only your server can open. - Choose Sign out, then Sign in again. OI asks for your email: its own session ended too.
When the access token expires, /account sends you to sign in again. While OI's own session is still open, that comes straight back without a password.
Before going live
- Use https for your app and for Otoko Identity. Only
localhostmay use http. The session cookie then getsSecure, fromAPP_URL. - Add your live addresses to the client, on its page in the console: the callback under Valid redirect URIs and the front page under Valid post-logout redirect URIs. They're compared exactly, character for character.
- Keep the client secret and
SESSION_SECRETout of git, in your host's secret settings. A leaked client secret is replaced on the client's Credentials tab; the old one keeps working for 24 hours, or stops at once if you say so. - Express and FastAPI: keep sessions in a real store (Redis, or your database) rather than in memory, so a restart or a second server doesn't sign everyone out. Next.js's sealed cookie needs no store.
- Never let the page's JavaScript see the tokens. The browser gets only the session cookie, which it can't read.
- Behind a proxy or a load balancer that ends https, as most hosts are, the code works as it is: the Express session trusts the proxy's
X-Forwarded-Protofor its cookie (proxy: true), and the Next.js routes build every address onAPP_URL, not on the address the request came in on.
If something goes wrong
| What you see | Why | What to do |
|---|---|---|
OI answers invalid_redirect_uri instead of showing its sign-in page | IDENTITY_REDIRECT_URI isn't on the client's list, exactly | Make it and the client's Valid redirect URIs the same, character for character. |
The callback fails with invalid_client | The client secret is wrong, rotated, or the client's Client authentication is off | Copy the current secret from the client's Credentials tab, and check Client authentication is on. |
The callback fails about state or nonce | The sign-in started in another browser, or the session cookie was lost on the way back | Start again from /auth/. Check that APP_URL matches the address in the browser, so the cookie is sent back. |
FastAPI says InsecureTransportError | OI is on plain http | On your own machine, set AUTHLIB_INSECURE_TRANSPORT=1. Use https anywhere else. |
Next.js next build stops on / or /account | The page reads the session while Next.js prerenders it | Keep export const instant = false on pages that read the session. |
| OI's sign-in page has no Register link | Allow sign-up is off on the client, or Sign-up allowed is off on the app | Turn them on, as in step 1. |
| Roles: none | roles isn't in the scopes, the person has no role yet, or they haven't signed in since getting it | Add roles to IDENTITY_SCOPES, give the role in the console, and sign in again. |
Tested with Express 5.3.0, express-session 1.19.0, tsx 4.23.15 · Next.js 16.4.6, iron-session 9.1.0 · openid-client 6.9.0 · FastAPI 0.165.0, Authlib 1.9.9, uvicorn 0.54.0, Python 3.14.