Node (Express) quickstart
By the end you will have an Express app with sign-in through authto.it, a protected /account page that shows
the signed-in person, and a sign-out that also ends the authto.it session. It uses
openid-client for the OpenID Connect parts and
express-session to keep the person signed in. Tested with Node 24.20, Express 5.3.0, express-session 1.19.0 and
openid-client 6.9.0.
1. Create the site
On the authto.it dashboard, open your organization and choose Add site:
- Name: anything, for example My app (local).
- Return address:
http://localhost:3000/auth/callback - After-sign-out address:
http://localhost:3000/ - Type: server-side (confidential). The site gets a client ID and a client secret. The secret is shown once, so copy it now.
A site can be invite-only (only the people you add can sign in) or open to anyone. Either works for this guide; on an invite-only site, add yourself first.
An AI tool connected to authto.it's MCP server can create the site for you, but the client secret is only issued on the dashboard.
2. Set up the project
mkdir my-app && cd my-app
npm init -y
npm pkg set type=module scripts.start="node --env-file=.env server.mjs"
npm install express express-session openid-client
Create the environment file with your site's values. SESSION_SECRET signs the session cookie; generate
one with node -e "console.log(crypto.randomBytes(32).toString('hex'))". Keep .env out of
version control.
.env
AUTHTO_ISSUER=https://letme.authto.it
AUTHTO_CLIENT_ID=your-client-id
AUTHTO_CLIENT_SECRET=your-client-secret
SESSION_SECRET=replace-with-a-long-random-string
node --env-file needs Node 20.6 or later. Variables already set in the environment take precedence over
the file. BASE_URL (the app's address, default http://localhost:3000) and PORT are optional here; set them in production.
3. Add the code
The whole app is one file. /login starts the sign-in with PKCE, state and
nonce; /auth/callback exchanges the code with the client secret and verifies the ID token;
/logout ends the local session and then the authto.it session.
server.mjs
import express from 'express';
import session from 'express-session';
import * as client from 'openid-client';
const BASE_URL = process.env.BASE_URL ?? 'http://localhost:3000';
const REDIRECT_URI = `${BASE_URL}/auth/callback`;
// Reads AUTHTO_ISSUER + /.well-known/openid-configuration
const config = await client.discovery(
new URL(process.env.AUTHTO_ISSUER ?? 'https://letme.authto.it'),
process.env.AUTHTO_CLIENT_ID,
process.env.AUTHTO_CLIENT_SECRET,
);
const app = express();
app.set('trust proxy', 1);
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: { httpOnly: true, sameSite: 'lax', secure: BASE_URL.startsWith('https:') },
}));
const esc = (s) => String(s ?? '').replace(/[&<>"']/g,
(c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
const page = (body) => `<!doctype html><meta charset="utf-8"><title>My app</title>${body}`;
// Sends signed-out visitors to sign-in, then back to the page they asked for.
function requireLogin(req, res, next) {
if (req.session.user) return next();
req.session.returnTo = req.originalUrl;
res.redirect('/login');
}
app.get('/', (req, res) => {
const user = req.session.user;
res.send(page(user
? `<p>Signed in as ${esc(user.name || user.email)}</p>
<p><a href="/account">Account</a></p>
<form method="post" action="/logout"><button>Sign out</button></form>`
: `<p><a href="/login">Sign in</a></p>`));
});
app.get('/account', requireLogin, (req, res) => {
const { sub, email, name, role } = req.session.user;
res.send(page(`<h1>Account</h1>
<p>sub: ${esc(sub)}</p><p>email: ${esc(email)}</p>
<p>name: ${esc(name)}</p><p>role: ${esc(role ?? '(none)')}</p>
<p><a href="/">Home</a></p>`));
});
app.get('/login', async (req, res) => {
const verifier = client.randomPKCECodeVerifier();
const state = client.randomState();
const nonce = client.randomNonce();
req.session.authto = { verifier, state, nonce };
const url = client.buildAuthorizationUrl(config, {
redirect_uri: REDIRECT_URI,
scope: 'openid email profile',
code_challenge: await client.calculatePKCECodeChallenge(verifier),
code_challenge_method: 'S256',
state,
nonce,
});
res.redirect(url.href);
});
app.get('/auth/callback', async (req, res, next) => {
const saved = req.session.authto;
delete req.session.authto;
if (!saved) return res.redirect('/login');
try {
// Checks state and iss, swaps the code (with the client secret),
// verifies the ID token (signature via JWKS, iss, aud, exp, nonce).
const tokens = await client.authorizationCodeGrant(
config,
new URL(req.originalUrl, BASE_URL),
{
pkceCodeVerifier: saved.verifier,
expectedState: saved.state,
expectedNonce: saved.nonce,
idTokenExpected: true,
},
);
const claims = tokens.claims();
const returnTo = req.session.returnTo ?? '/';
// New session id at sign-in; keep only what the app needs.
req.session.regenerate((err) => {
if (err) return next(err);
req.session.user = {
sub: claims.sub, // permanent per site: key your users on this
email: claims.email, // absent for phone sign-in
name: claims.name,
role: claims.role, // set on the authto.it dashboard; may be absent
};
req.session.idToken = tokens.id_token;
req.session.save(() => res.redirect(returnTo));
});
} catch (err) {
next(err);
}
});
app.post('/logout', (req, res, next) => {
const idToken = req.session.idToken;
req.session.destroy((err) => {
if (err) return next(err);
res.clearCookie('connect.sid');
if (!idToken) return res.redirect('/');
// End the authto.it session too, then come back to the home page.
const url = client.buildEndSessionUrl(config, {
id_token_hint: idToken,
post_logout_redirect_uri: `${BASE_URL}/`,
});
res.redirect(url.href);
});
});
app.listen(Number(process.env.PORT ?? 3000), () => console.log(`Listening on ${BASE_URL}`));
authorizationCodeGrant checks state and the iss parameter on the callback, sends
the code with the PKCE verifier and client secret, and verifies the ID token: signature against the keys at
/jwks.json, iss, aud, exp and nonce. If any check
fails it throws, and Express shows an error instead of signing anyone in.
sub is permanent for a person on a site. If the app has its own users table, key it on sub,
not on the email address, which the person can change.
4. Try it
npm start
Open http://localhost:3000/ and choose Sign in. You land on authto.it's
sign-in page. Enter your email address, type the code authto.it sends you, and you are back on the home page,
signed in. Account shows your sub, email, name and role. Sign out signs you out of the app
and of authto.it and returns you to the home page.
If authto.it shows an error instead of the sign-in page, the return address does not match the one on the site exactly (check the port and the path).
5. Protect pages and use the role
Add requireLogin to any route that needs a signed-in person:
app.get('/reports', requireLogin, (req, res) => {
res.send(`Reports for ${esc(req.session.user.email)}`);
});
role is set per person on the authto.it dashboard and arrives in the ID token. It may be absent, so treat
a missing role as the least access:
function requireRole(role) {
return (req, res, next) => {
if (!req.session.user) return requireLogin(req, res, next);
if (req.session.user.role !== role) return res.status(403).send('Forbidden');
next();
};
}
app.get('/admin', requireRole('admin'), (req, res) => {
res.send('Admins only');
});
The role is read at sign-in. After you change someone's role on the dashboard, it applies the next time they sign in.
Going live
- On the site, add the production return address (
https://example.com/auth/callback) and after-sign-out address (https://example.com/). Both must match exactly. - Set
BASE_URL=https://example.comand the other variables in the server's environment, not in a file in the repository. Keep the client secret on the server only. - Serve the app over HTTPS. With an
httpsBASE_URLthe session cookie is markedSecure;trust proxylets that work behind a reverse proxy that terminates TLS. - express-session's default memory store is for development only. Use a production store such as Redis
(
connect-redis) or your database. - Ask for
offline_access(a refresh token) only if the app calls APIs on the person's behalf while they are away. Signing people in does not need it. - Manage who can sign in, and each person's role, on the authto.it dashboard.