One Express API for web and mobile, without two auth models
One Express API for Next.js and Expo. Cookies on the web and Bearer tokens on native, plus CORS for Expo web, Socket.IO auth and API versioning.
Sosifie has a Next.js app and an Expo app in one frontend monorepo, both talking to one Express API. The web app already logged in with httpOnly cookies. I wanted one API, one user table and one set of sessions for both, without moving the web app to localStorage, and app auth built for a phone.
Cookies on the web, a header on native
On the web, script in the page can't read an httpOnly cookie, and the browser attaches it on its own. The cost is CSRF, which SameSite and Origin checks handle.
A native app doesn't have the browser's page-script model, but its dependencies can still compromise a token. Store tokens in the Keychain on iOS or Keystore-backed encrypted storage on Android.
React Native's fetch does handle cookies, but I didn't want login to depend on how iOS and Android persist a Set-Cookie. So the app keeps the token and sends Authorization: Bearer .... A browser never adds that header by itself, which protects the Bearer path from CSRF.
A shared /auth router and middleware
Both clients share the account, the password check and the backend sessions. The native routes are in the same /auth router and call the same service functions. Protected routes go through one middleware that takes the token from the cookie or the header and verifies it.
The cleaned-up example below records which path was used, because only the cookie path needs a CSRF check. Sosifie doesn't run this version:
// middleware/auth.ts
import type { Request, Response, NextFunction } from 'express'
import jwt from 'jsonwebtoken'
import { allowedOrigins } from '../config/origins'
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
export function requireAuth(req: Request, res: Response, next: NextFunction) {
const header = req.headers.authorization
const bearer = header?.startsWith('Bearer ') ? header.slice(7) : undefined
const token = bearer ?? req.cookies?.access_token
if (!token) return res.status(401).json({ code: 'NO_TOKEN' })
// A cookie rides along on cross-site requests, a header never does
if (!bearer && !SAFE_METHODS.has(req.method)) {
const origin = req.headers.origin
if (!origin || !allowedOrigins.has(origin)) return res.status(403).json({ code: 'BAD_ORIGIN' })
}
try {
// Full signature check with a pinned algorithm, on every route
res.locals.user = jwt.verify(token, process.env.JWT_SECRET!, { algorithms: ['HS256'] })
res.locals.authVia = bearer ? 'bearer' : 'cookie'
next()
} catch {
res.status(401).json({ code: 'TOKEN_INVALID' })
}
}
The paths only split at login and refresh. The web endpoints set cookies. The native ones return tokens in the JSON body for secure storage. With separate routes, a web response never contains a token.
The refresh part below is the design I'd recommend, not code Sosifie runs today (rotation is covered in my post on refresh tokens in the Next.js App Router). Login returns a short-lived access token and an opaque refresh token, which the server looks up by hash and rotates. One rotation function and one table of hashes serve both paths, so "log out this device" works the same everywhere.
// routes/auth.native.ts
router.post('/auth/native/login', loginLimiter, async (req, res) => {
const user = await authService.checkPassword(req.body.login, req.body.password)
if (!user) return res.status(401).json({ code: 'INVALID_CREDENTIALS' })
const session = await sessions.create(user.id, { client: 'native' })
const tokens = await sessions.issueTokens(session) // { accessToken, refreshToken, expiresIn }
res.json({ user: publicUser(user), ...tokens })
})
router.post('/auth/native/refresh', refreshLimiter, async (req, res) => {
const raw = req.body?.refreshToken
if (typeof raw !== 'string') return res.status(401).json({ code: 'SESSION_EXPIRED' })
try {
// Hash lookup, reuse detection, rotation: the same code the cookie flow calls
res.json(await sessions.rotate(raw))
} catch {
res.status(401).json({ code: 'SESSION_EXPIRED' })
}
})
Tokens on the app live in SecureStore
Tokens go into expo-secure-store (Android, iOS and tvOS, not web). Sosifie's shared API client package takes a getAccessToken function instead of reading storage itself, and on a 401 apps/mobile/src/lib/api.ts runs one refresh through a shared promise and retries once, so ten failing requests still cause one refresh. With rotating refresh tokens, a second refresh would send a token the first one already replaced. Sosifie's app only stores the access token, though: /auth/mobile/refresh takes the expired access token as a Bearer header and checks the session kept on the server. The sketch below is for the refresh-token design above:
// tokens.ts (sketch for the refresh-token design above)
import * as SecureStore from 'expo-secure-store'
const API_URL = process.env.EXPO_PUBLIC_API_URL
const [ACCESS, REFRESH] = ['auth.access', 'auth.refresh']
export const getAccessToken = () => SecureStore.getItemAsync(ACCESS)
export const clearTokens = () =>
Promise.all([SecureStore.deleteItemAsync(ACCESS), SecureStore.deleteItemAsync(REFRESH)])
let refreshing: Promise<string | null> | null = null
export function refreshOnce(): Promise<string | null> {
refreshing ??= (async () => {
const refreshToken = await SecureStore.getItemAsync(REFRESH)
if (!refreshToken) return null
const res = await fetch(`${API_URL}/auth/native/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refreshToken }),
})
if (res.status === 401) return clearTokens().then(() => null) // server said no
if (!res.ok) throw new Error(`refresh failed: ${res.status}`) // network or 5xx: keep tokens
const tokens = await res.json()
await SecureStore.setItemAsync(ACCESS, tokens.accessToken)
await SecureStore.setItemAsync(REFRESH, tokens.refreshToken) // the old one is dead now
return tokens.accessToken as string
})().finally(() => { refreshing = null })
return refreshing
}
iOS Keychain items can still be there after a reinstall (Android's aren't), so a token found on first launch is only a hint. Anything prefixed EXPO_PUBLIC_ is inlined into the bundle: fine for the API URL, never for a secret.
Expo web is still a browser. Sosifie's app currently falls back to localStorage there and sends the same Bearer header, which is what the web app was avoiding. The cookie path, as on Next.js with credentials: 'include', fits it better. On a different site from the API, that cookie needs SameSite=None; Secure and hits third-party cookie blocking, so keep it on the same site.
CORS only matters for code in a browser
Native apps don't enforce CORS or send a browser-style Origin. The list only needs the Next.js site, the Expo web dev server (Metro uses port 8081 by default), the web export and preview deploys. During the Expo work I changed three files (env config, app.ts, socket.ts) to turn the hardcoded array into a Set merged with a CORS_ORIGINS variable.
// config/origins.ts
const fromEnv = (process.env.CORS_ORIGINS ?? '')
.split(',')
.map((o) => o.trim())
.filter(Boolean)
const devOrigins = ['http://localhost:3000', 'http://localhost:8081'] // Next.js, Expo web
export const allowedOrigins = new Set([
'https://app.example.com',
...(process.env.NODE_ENV === 'production' ? [] : devOrigins),
...fromEnv, // Expo web export, preview deploys
])
// app.ts
app.use(
cors({
origin(origin, cb) {
// No Origin: native apps, curl, server-to-server. CORS has nothing to say about them.
if (!origin) return cb(null, true)
cb(null, allowedOrigins.has(origin))
},
credentials: true,
allowedHeaders: ['Content-Type', 'Authorization'],
})
)
With credentials: true you can't use *: per MDN, the server must answer with a specific origin or the browser blocks the response and ignores its Set-Cookie. origin: true makes the cors package echo any origin back, which switches off the protection for a cookie-based API.
When cors refuses an origin it only leaves the headers off. The handler still runs the request, and for this reason the middleware above checks Origin itself on the cookie path.
Socket.IO shares the origins and the token
Socket.IO's cors option should use the same set. In Sosifie, socket.ts still repeats the list instead of importing it. Per its docs, that option only affects HTTP long-polling, and WebSocket connections aren't subject to CORS. Handshake auth decides who gets in. The web client connects with withCredentials: true but also passes the token in auth (the Socket.IO post explains why), and the native client passes the token in the auth payload.
// socket.ts
const io = new Server(httpServer, {
path: '/api/socket',
cors: { origin: [...allowedOrigins], credentials: true }, // long-polling only
})
io.use((socket, next) => {
const cookies = cookie.parse(socket.handshake.headers.cookie ?? '')
const token = socket.handshake.auth?.token ?? cookies.access_token
if (!token) return next(new Error('unauthorized'))
try {
socket.data.user = jwt.verify(token, process.env.JWT_SECRET!, { algorithms: ['HS256'] })
next()
} catch {
next(new Error('unauthorized'))
}
})
The Expo socket provider needed three fixes in a row: teardown, the reconnect lifecycle, and a race when connecting while the app was in the background. The app now disconnects in the background and reconnects in the foreground. On an auth error it refreshes and retries once. It writes the current token into socket.auth before each manual connect, but automatic reconnects reuse whatever token is there. The sketch below uses the function form of auth. With it, every reconnect reads the current token.
// socket.ts (sketch; Sosifie's version is apps/mobile/src/providers/SocketProvider.tsx)
let authRetried = false
export const socket = io(SOCKET_URL, {
path: '/api/socket',
transports: ['websocket', 'polling'],
autoConnect: false,
auth: (cb) => { void getAccessToken().then((token) => cb({ token })) },
})
socket.on('connect', () => { authRetried = false })
socket.on('connect_error', async (err) => {
// A middleware rejection doesn't auto-reconnect, so retry by hand, once
if (err.message !== 'unauthorized' || authRetried) return
authRetried = true
if (await refreshOnce()) socket.connect()
})
AppState.addEventListener('change', (state) => {
if (state === 'active') socket.connect()
else socket.disconnect()
})
The handshake is checked once. A connected socket stays connected after its token expires. If that matters, disconnect it server-side around exp.
Old app builds keep running for months
An old native build keeps running on phones that don't update, sometimes for months. expo-updates only reaches builds with a matching runtime version, after the app downloads the update. So existing routes are additive, never renaming or removing a field an older build reads, and anything breaking goes into a /v2 next to the old routes. Auth endpoints change last, because an old build that can't refresh logs out all its users at once.
I'd have the app send Application.nativeApplicationVersion from expo-application in an X-App-Version header, with a middleware that compares it to a minimum version and answers APP_UPDATE_REQUIRED (426 is a common pick). The screen for that code has to be in the first release.
The backend README documents the native endpoints and the expired-session error format, with mobile UI gaps tracked in a parity doc. I got versioning wrong. Sosifie's routes are under a plain /api prefix. Starting over, I'd add a version segment on day one, since adding it later means running both paths side by side for a while.
More posts
- 01
Deploying Next.js and NestJS to AWS EC2 with Docker Compose
How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.
- 02
How I store OAuth tokens for social media APIs in NestJS
OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.
- 03
llms.txt on my Next.js site, and now Lighthouse grades it
vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.