18 October 2026
Authentication in JavaScript: Secure Login, Sessions, and API Access

TL;DR
JavaScript can collect credentials and make authenticated requests, but the server must verify identity, maintain or validate a session, and authorize each requested resource. For a same-origin browser app, a server-controlled session in a Secure, HttpOnly cookie is a useful starting pattern; protect state-changing requests against CSRF and treat injected JavaScript as a separate threat. Use bearer credentials deliberately for API clients, not because a JWT seems more modern. We show both the browser flow and a small owner-scoped db3.ai route below.
Authentication in JavaScript is often described as adding a login form, installing a library, or checking whether a token exists. None of those establishes a trustworthy boundary by itself. A browser can render a sign-in screen and remember what to display, but its code, requests, and locally stored values are under the user's control. The application server or trusted identity provider has to establish identity, and the resource server must make its own access decision.
If you are building a multi-user application, trace one request all the way from credentials to the particular note, workspace, or API operation it touches. That reveals where a valid login stops being enough. OWASP's session management guidance treats authentication, session management, and access control as related but distinct responsibilities.
Table of contents
- What does authentication in JavaScript actually mean?
- Follow a login from browser to private record
- Protect the password and the recovery path
- Choose the session transport to match the client
- Where do OAuth, OpenID Connect, and passkeys fit?
- A small JavaScript example with a real server boundary
- Check the API boundary before shipping
- Frequently asked questions
- Build the boundary before the login UI
- Sources
- Recommended Reads
What does authentication in JavaScript actually mean?
Authentication answers who is making this request? The user might prove that through a password, a passkey, or an external identity provider. Session management connects a successful sign-in to later requests. Authorization asks whether that authenticated caller may perform this action on this resource. A route that requires login but accepts any note ID has implemented the first check and skipped the last. OWASP calls the latter failure broken object-level authorization.
Think about a note owned by account A. Account B may have a perfectly valid session, yet must not be able to fetch A's note by changing the ID in a URL. Hiding the note link in JavaScript is a useful interface choice, not an access rule. The API must verify the session and constrain its lookup by the trusted account or an explicit workspace policy.
Different teams put these pieces in different places. A same-origin web application can keep the browser-facing session at its own backend; a separate API may validate a bearer credential; a federated sign-in can establish identity through an external provider before the application starts its own session. The security question is not which JavaScript framework displays the form. It is which trusted component verifies each claim, how long that proof remains valid, and what the proof permits.
Follow a login from browser to private record
A password-based browser flow has five meaningful boundaries:
- Submit credentials over HTTPS. Browser code sends the password to the application's login endpoint. Client-side validation may improve feedback, but the server validates the request independently. OWASP recommends TLS for both login and subsequent authenticated pages.
- Verify the credential. The server finds the account's credential record and checks the supplied password using its password-hashing implementation. It handles wrong credentials without disclosing whether the account exists.
- Issue a new session. After success, the server creates unpredictable, time-limited session proof and sends it via the chosen transport. A browser cookie can carry an opaque identifier or bearer value; a signed token is another format, not an automatic security upgrade.
- Authenticate every protected request. The browser sends its cookie with eligible requests. The server checks expiration and revocation before deriving the caller's identity. A user ID supplied in JSON cannot substitute for this step.
- Authorize the requested operation. The server checks ownership, membership, role, or another product-specific rule before it reads or changes data. Revocation at logout and policy changes must affect later requests.

The important separation is between proving a caller and allowing a particular operation. In our browser-to-database login walkthrough, the generated application puts an opaque bearer session in an HttpOnly cookie. Its protected routes authenticate that cookie; note routes then scope data to the authenticated user. These are application-owned routes and policy, not endpoints installed automatically by the Auth service.
Protect the password and the recovery path
Do not store passwords as plaintext or use a fast general-purpose hash such as SHA-256 as your password-storage strategy. OWASP recommends adaptive password hashing, including Argon2id where available, with an appropriate unique salt and configured work factors. Use a maintained authentication component rather than hand-rolling password comparisons or cryptographic formats. Hashing protects stored credentials; it does not replace HTTPS, which protects the password and session in transit.
Login defenses have to account for guessing and abuse. Validate body shape and length server-side, apply rate limits appropriate to your deployment, return generic bad-credential responses, and keep passwords, reset tokens, and session values out of logs. Consider additional verification for sensitive account changes. Process-local throttling in a single development process is not a distributed rate limit: multiple production instances need a shared or upstream enforcement plan. OWASP's authentication checklist covers credential attacks and reauthentication.
Recovery is part of authentication architecture, not a secondary email feature. A reset request should respond consistently whether or not the address exists; the recovery token should be unpredictable, short-lived, and single-use. After a successful reset, decide how to revoke outstanding sessions and notify the account owner. A reset link or password emailed to a user should never become a reusable login credential. OWASP's forgot-password guidance details those boundaries. Our db3.ai Auth guide documents its reset and session-revocation service behavior, while the consuming app remains responsible for recovery delivery and public routes.
Choose the session transport to match the client
For a same-origin browser application, we generally start by considering an opaque, server-controlled session carried in a cookie. The cookie should be scoped as narrowly as practical, use Secure in production, and use HttpOnly so browser JavaScript cannot read its value. Specify a deliberate SameSite policy, expiration, and logout behavior. Avoid an unnecessary Domain attribute when a host-only cookie meets the product's needs. MDN documents these cookie attributes and their scope.
HttpOnly does not make an application immune to cross-site scripting: injected same-origin code can still make requests as the user and read accessible responses. Nor does SameSite alone constitute a complete CSRF policy. Cookies are sent automatically with eligible requests, so state-changing operations need an appropriate defense, such as a server-validated CSRF token or a carefully designed origin and Fetch Metadata policy. Do not use GET for mutations. Test login and logout flows as well as ordinary writes. OWASP's CSRF prevention guide explains the options and warns that XSS can defeat CSRF mitigations.
For a separate API or non-browser client, a bearer credential in an Authorization header may make more sense. That choice shifts the problem to secure issuance, storage, validation, scope, and revocation. A bearer token is usable by whoever possesses it. A JWT can be signed without being encrypted, so do not put secrets in a readable token payload; validate its issuer, audience, signature, expiry, and permitted use with a trusted implementation. Prefer short-lived access and a deliberate refresh strategy. A server-to-server caller should use its own appropriately scoped service identity, not a copied employee browser session.

Do not treat localStorage as a safe vault for long-lived bearer credentials. JavaScript running in the origin can read it, including malicious code injected through XSS. Keeping tokens only in memory narrows persistence but does not stop compromised in-origin code from using the current app. A backend-for-frontend can keep OAuth tokens server-side and expose a browser session instead, when that architecture fits. The IETF browser-app OAuth guidance analyzes malicious JavaScript, token theft, and browser architecture choices.
The db3.ai starter is a concrete cookie-transport example, not a claim that every client should use a cookie. Its login walkthrough documents a host-only HttpOnly cookie, production Secure, SameSite=Lax, and strict Origin checks on state-changing requests. That Origin requirement also means a non-browser client must intentionally satisfy the starter's contract or use a separately designed API; adding CORS alone does not redesign authentication or CSRF protection.
Where do OAuth, OpenID Connect, and passkeys fit?
OAuth 2.0 is an authorization framework for access to protected resources. OpenID Connect (OIDC) adds an identity layer for sign-in on top of OAuth 2.0; it is useful when users authenticate through another provider. An OAuth access token for a third-party API is not interchangeable with your application's login session. Validate the identity result, link it to an application account under an explicit policy, then apply your own record-level authorization. The OpenID Connect Core specification defines that identity layer.
For an OAuth client running directly in a browser, the IETF's browser-based applications guidance recommends the authorization-code flow with PKCE rather than the older implicit flow. A browser cannot keep a client secret private. Decide whether your frontend truly needs access tokens, or whether a backend should handle the token exchange and retain tokens while the browser uses a protected app session. Review redirect handling, token scope, lifetime, and refresh behavior with the provider you select.
Passkeys use WebAuthn's public-key credentials and can replace or strengthen password sign-in. The browser participates in creating or obtaining a credential, but the server still issues a challenge, verifies the returned assertion against the registered public key, and establishes the session. Recovery, account binding, and lost-device behavior require their own design. MDN's Web Authentication API guide describes this browser-and-server handshake. A passkey changes how the user proves identity; it does not decide whether they may view another tenant's data.
A small JavaScript example with a real server boundary
The following browser example assumes you have created an account in the generated db3.ai Notes starter, installed its currently documented preview packages, configured MariaDB, applied committed migrations, and started the app on its documented origin. Run this in the starter's same-origin browser context, with your own local test credentials passed as arguments. It calls the starter's application routes; these are not universally registered by @db3.ai/app. It does not write secrets to storage or print them to the console. Starter setup and login route documentation describe the required application and routes.
// Run inside the generated starter's same-origin browser, not another site.
async function signInAndLoadNotes(email, password) {
const login = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
if (!login.ok) throw new Error('Sign-in failed.');
const identity = await fetch('/api/me');
if (!identity.ok) throw new Error('Could not check session.');
const { user } = await identity.json();
if (!user) throw new Error('Session is no longer active.');
const records = await fetch('/api/notes');
if (!records.ok) throw new Error('Could not load notes.');
const { notes } = await records.json();
return { user, notes };
}
The browser's default Fetch credentials mode is same-origin, so the browser can attach an eligible same-origin cookie and accept the login response's Set-Cookie; JavaScript does not need to read the session value. MDN documents the Fetch credential modes. The snippet intentionally omits form handling, password collection, UI error messaging, and a cross-origin deployment. It assumes the starter's server-side Origin validation, body validation, rate limits, password verification, session issuance, and request-context setup are already in place. Do not copy only this client function into an app without its trusted server.
A separate server excerpt shows the access boundary for an individual note. This is from inside the generated starter's Fastify createServer implementation, after application boot, request-context setup, cookie handling, schemas, and error mapping. The starter supplies server, application, Note, requireUser, and HttpError; requireUser is a helper in its own HTTP application, not an exported framework auth guard. The underlying pattern is portable even if those identifiers are not. The owned-note API guide includes the complete handler and its test context.
// Inside the starter's server/http/createServer.ts, not a standalone module.
server.get<{ Params: { id: string } }>('/api/notes/:id',
{ schema: { params: noteParams } }, async request => {
const user = await requireUser(application, request);
const note = await Note.where({
id: request.params.id,
owner: user.id,
}).first();
if (!note) throw new HttpError(404, 'Note not found.');
return { note: note.toJSON() };
});
The session establishes the caller. The query then enforces the owner's ID in the data access itself. If the note belongs to another account or does not exist, the response is the same 404. A tenant-based app needs a different, explicit membership and resource rule; swapping in a user-supplied tenant ID does not establish trust. We have reviewed the documented route and starter test context, not executed this excerpt independently. Request-local authentication state must stay inside the starter's request context; do not hoist it into a global variable shared by concurrent requests.
Check the API boundary before shipping
Use tests that exercise denial as well as success:
- Identity: Unknown credentials fail without confirming account existence. Expired and revoked sessions fail on a later request. Logout revokes the server-side credential, not merely the browser's copy.
- Authorization: User A can read A's record. User B cannot read, edit, delete, export, or act on A's record by changing its ID. Repeat for tenant membership, role changes, and administrative actions. OWASP recommends object-level checks wherever a client-selected ID drives an operation.
- Browser defenses: HTTPS is enforced; cookie flags match the environment; state-changing requests reject forged origins or invalid CSRF proofs; XSS defenses cover untrusted content and third-party scripts. An HttpOnly cookie limits token reading, not arbitrary in-origin actions.
- Recovery and operations: Reset tokens expire after one use; existing sessions follow a documented invalidation policy; logs redact passwords and tokens; production rate limits work across your deployed instances; alerts distinguish abuse from infrastructure failures.
- Other clients and workers: Each API client has a suitable credential type and scope. Background jobs and AI tools derive trusted actor and resource IDs from application context and recheck the relevant policy when they run, instead of inheriting a browser session or trusting model-supplied IDs.
For the provided starter, the owned-note guide links to request tests that exercise cross-user denial and real persistence. Use a disposable test database and adapt those tests to your own schema. The documentation's tests are evidence of the starter's intended behavior, not a claim that your modified application or this excerpt was run here.
Frequently asked questions
Is authentication the same as authorization?
No. Authentication identifies the caller; authorization checks whether that caller can perform an action on a specific record, tenant, or operation. Hiding a button in JavaScript never replaces the server-side check. OWASP's API1 guidance describes failures that affect fully authenticated users.
Should I use a cookie or a JWT for a JavaScript app?
Choose based on the client and the session lifecycle. A same-origin browser often benefits from a protected cookie and server-controlled revocation; a separate API client may need a scoped bearer token. A JWT is one possible bearer-token format, not a substitute for expiry, safe storage, revocation planning, CSRF defense when carried in a cookie, or resource authorization. OWASP's session guidance is a useful baseline for the trade-offs.
Is HTTP Basic authentication the same as OAuth?
No. HTTP Basic presents credentials to a server with requests; OAuth is a framework for delegated access to protected resources. Neither makes an endpoint safe without HTTPS and appropriate authorization. If you want users to sign in through an external provider, evaluate OIDC rather than treating a generic OAuth access token as proof of identity. OpenID Connect Core specifies the identity layer.
Build the boundary before the login UI
We would make the first design review a two-account test: sign in, fetch an owned record, retry its ID as another account, and retry after logout. This surfaces three different failure modes without forcing your product into a particular JavaScript framework. If you want to inspect the integrated TypeScript implementation, begin with db3.ai's Auth guide, then follow the browser-to-database walkthrough and adapt its owned-record policy to your own data. Check current preview package access before planning a production rollout.
Sources
- OWASP Authentication Cheat Sheet
- OWASP Password Storage Cheat Sheet
- OWASP Forgot Password Cheat Sheet
- OWASP Session Management Cheat Sheet
- OWASP Cross-Site Request Forgery Prevention Cheat Sheet
- OWASP API1:2023 Broken Object Level Authorization
- IETF RFC 10017, OAuth 2.0 for Browser-Based Applications
- OpenID Connect Core 1.0
- MDN, Using HTTP cookies
- MDN, Request credentials
- MDN, Web Authentication API
- db3.ai Auth guide
- db3.ai starter setup
- db3.ai browser-to-database login walkthrough
- db3.ai owned-note API guide
Recommended Reads
- How to Create TypeScript APIs With Clear Boundaries, Authentication, and Tests: Carry identity through validated routes and owner-scoped services.
- 4 TypeScript Authentication Frameworks Compared: Sessions, Permissions, and Backend Fit: Compare framework integration and operating responsibility.
- 5 Application Authentication Services Compared for Multi-User Products: Explore hosted and self-operated identity options.