Architecture
One API, four clients, no exposed backend
A customer site, an admin panel, an agent portal and a mobile app against one Express API. Three of them get an intermediary and one does not, and that asymmetry decides almost every security choice in the system.
One Express API serves four applications: the customer facing site, an admin panel, an agent portal, and a React Native app. They have different audiences, different trust levels, and different deployment shapes, and they all hit the same routes and the same database.
The obvious design is to publish the API on a domain and let all four call it. That works, and it hands anybody who opens devtools the complete surface area of your backend, including the routes they are not supposed to know exist. Here is the arrangement I ended up with instead, and the one asymmetry that shaped all of it.
Group routes by audience, not by resource
The mounting table is the whole access control story at a glance:
app.use("/api/auth", require("./routes/auth"))
app.use("/api/brands", require("./routes/brands"))
app.use("/api/quotes", require("./routes/quotes"))
app.use("/api/orders", require("./routes/orders"))
// ...seventeen public-facing groups
app.use("/agent", require("./routes/agent"))
app.use("/admin/device-uploads", require("./routes/admin-device-uploads"))
app.use("/admin", require("./routes/admin"))Everything a customer or the mobile app can reach lives under /api. Everything staff-only lives under /agent or /admin. That is not decoration: because the prefix maps to the audience, any middleware that needs to behave differently for internal traffic can branch on the path alone, without knowing anything about routes.
Grouping by resource instead, with users, orders and devices each holding a mix of public and admin endpoints, makes that impossible. Every cross-cutting rule then has to enumerate individual routes, and every new route is an opportunity to forget one.
Note also that the more specific admin mount comes before the general one. Express matches in order, so reversing those two lines would silently route device uploads into the general admin router.
The browser never learns the backend origin
Each browser client is a Next.js application, which means it has a server of its own. That server is the only thing that knows where the API lives.
export async function GET(request: Request) {
const { searchParams } = new URL(request.url)
const deviceType = searchParams.get("deviceType") ?? searchParams.get("deviceTypeId")
try {
const res = await fetch(
`${process.env.SERVER_URL}/api/brands${deviceType ? `?deviceType=${encodeURIComponent(deviceType)}` : ""}`,
{ method: "GET", headers: { "Content-Type": "application/json" } },
)
if (!res.ok) return new NextResponse("Failed to fetch brands", { status: res.status })
return NextResponse.json(await res.json())
} catch (err) {
console.error("Error in brands route.ts:", err)
return new NextResponse("Internal server error", { status: 500 })
}
}The browser calls its own origin. The network tab shows requests to the site the visitor is already on. Nothing anywhere in the shipped JavaScript names the backend, so there is nothing to point a scanner at, and the API can sit somewhere that is not addressable from the public internet at all.
There are three secondary benefits that turned out to matter as much as the primary one. Cross-origin configuration disappears, because there is no cross-origin request. Tokens can live in httpOnly cookies scoped to the app's own domain rather than in JavaScript-readable storage. And the proxy layer is a natural place to normalise the two spellings of a query parameter, as that handler is quietly doing, without touching the API.
The cost is honest and worth stating: 33 small handlers is 33 files that mostly forward a request, and each is a place a header can be dropped or a status code mishandled. If I were starting again I would generate the boring ones from a manifest and hand-write only the ones that do something, because a hand-written passthrough is a hand-written bug waiting for its parameter.
The asymmetry: one client has no intermediary
This is the part that shapes everything else.
The three browser clients each have a server in front of them. The React Native app does not. There is no Next.js layer between the phone and the API, so the app must call the backend directly, which means the backend must be reachable from the public internet, which means the whole careful arrangement above has a door in it.
There is a second, sharper consequence. A web bundle is obfuscated and awkward to inspect. A mobile binary can be pulled off a device and decompiled at leisure, on hardware the attacker owns, with no rate limit and no logging. Anything the app knows, an attacker eventually knows: the base URL, the header names, every endpoint it calls.
A client with no intermediary is a client you cannot keep secrets from. Design for the assumption that its entire API surface is public knowledge, because it is.
So the mobile app gets the same authentication and the same server side authorisation as everyone else, and nothing is defended by being hard to find. What it does get is an acknowledgement that it is different:
const skipObfuscate =
req.path.startsWith('/admin') ||
req.path.startsWith('/agent') ||
req.path.startsWith('/api/auth') ||
req.path.startsWith('/api/upload') ||
req.path === '/health' ||
req.headers['x-client'] === 'mobile'Public API responses have their JSON keys shortened, which is friction against casual scraping. The mobile app opts out with a header, because it is a first party client and readable responses are worth more than friction it would have to undo anyway. That header is trivially forgeable, which is fine: it disables an obfuscation layer that was never a security control, and nothing else.
Same process, different public surface
Because the app forces the API to be publicly reachable, the API is deployed on two hostnames: an internal one the proxies use, and a public one the app uses. A guard makes them behave differently.
function getAllowedPublicPaths() {
return ["/health", "/api/auth/google", "/api/auth/google/callback"]
}
return (req, res, next) => {
const requestHost = getRequestHost(req)
if (requestHost === publicApiHost && !isAllowedPublicPath(req.path)) {
return res.status(403).json({ error: "Route is not available on public API host" })
}
next()
}On the public hostname, only health and the Google OAuth callback are reachable. Everything else, including every admin and agent route, returns 403 regardless of what credentials are presented. One process, one codebase, two very different attack surfaces, decided by the Host header.
The OAuth callback is the reason a mechanism like this is needed at all. It has to be on a publicly resolvable URL because Google redirects a browser to it, so it cannot hide behind the proxy layer with everything else. Rather than making an exception in the architecture, it is an exception in a list.
Two implementation details worth copying. The host is read from x-forwarded-host before falling back to host, because behind a load balancer the raw Host header is the balancer's. And the guard is behind an environment flag that defaults to off, so local development and single-host deployments are unaffected. A security control that breaks your development environment gets disabled and stays disabled.
Where this design is weak
Three things, in the order I would fix them.
The guard is a deny-by-exception list, so a new route is public-host-blocked by default, which is the safe direction. But the allowed list is a hardcoded function rather than configuration, so adding a legitimately public route means a deploy. That is a mild annoyance rather than a risk, and I would leave it, because the alternative is a config file where a typo opens the admin panel.
The obfuscation exclusions are prefix matches on req.path, evaluated before routing. A path that merely starts with /api/upload gets excluded whether or not it resolves to the upload router. Prefix matching against paths is always slightly looser than it looks, and if the exclusion were doing security work rather than cosmetic work, that would matter.
And the proxy layer means every request to a browser client costs two network hops instead of one. On the same network that is a millisecond or two, and it is real. The mitigation is to proxy only what the browser needs at request time and let the Next.js server fetch the rest during rendering, where it is already making calls and the extra hop is free.
What to take from this
- Group routes by audience, so cross-cutting rules can branch on a path prefix instead of enumerating endpoints.
- Mount specific prefixes before general ones. Express matches in order and will not warn you.
- Proxy browser traffic through the client's own server, and keep the backend URL in a server-only variable.
- Take the free wins that come with it: no CORS, httpOnly cookies on your own domain, and a place to normalise inputs.
- Generate boring passthrough handlers rather than hand-writing dozens of them.
- Identify which clients have no intermediary and design assuming their entire API surface is public.
- Never let a header decide anything that matters. A first party header is a hint, not a credential.
- Split the public surface from the internal one by hostname, with an explicit allowlist for the few routes that must be reachable.
- Read x-forwarded-host before host, and put the whole guard behind a flag that is off by default.
The organising idea is that not every client deserves the same trust, and the honest way to express that is in the network topology rather than in a comment. Three of these applications get to hide behind a server. One cannot, so it gets designed as though everything it knows is already published, because it is. The rest of the platform, including the admin panel and agent portal this serves, is written up in the SellPrime case study.