Native email and password authentication on Cloudflare Workers
By Flavio
Tagged: Cloudflare
Build native email/password auth on Cloudflare Workers with peppered PBKDF2 hashes, D1 sessions, and hardened HttpOnly cookies.
You don’t need a separate auth server to build email and password authentication on Cloudflare. Between the Web Crypto API in Workers, D1 for SQL storage, and regular browser cookies, you already have all the pieces.
Wiring up the routes is straightforward. What really matters is making sure the database never holds raw passwords or usable session tokens. We’ll store salted, peppered PBKDF2 hashes for passwords and SHA-256 hashes for sessions, so even a full dump of your D1 database won’t give anyone a way to log in.
What we are building
Our Worker handles four endpoints:
| Endpoint | Job |
|---|---|
POST /api/register | Create the user and start a session |
POST /api/login | Verify the password and start a session |
GET /api/me | Return the signed-in user |
POST /api/logout | Delete the session |
I’m not going to paste a full Worker file into this post, because most of it would be request parsing, routing, and error handling boilerplate. We’ll focus on the parts that are easy to get wrong: passwords, sessions, cookies, and request protection.
Create the Worker and the database
Start by creating a new TypeScript Worker project:
npm create cloudflare@latest -- native-auth-worker
cd native-auth-worker
Next, create a D1 database for your users and sessions:
npx wrangler d1 create native-auth
Add the database binding and the required secret name to wrangler.jsonc:
{
"name": "native-auth-worker",
"main": "src/index.ts",
"compatibility_date": "2026-07-30",
"secrets": {
"required": ["PASSWORD_PEPPER"]
},
"d1_databases": [
{
"binding": "DB",
"database_name": "native-auth",
"database_id": "YOUR_DATABASE_ID"
}
]
}
Then generate the TypeScript binding types from that config:
npx wrangler types
Create the tables
You only need two tables here, one for users and one for active sessions:
create table users (
id text primary key,
email text not null collate nocase unique,
password_hash text not null,
created_at integer not null
);
create table sessions (
token_hash text primary key,
user_id text not null references users(id) on delete cascade,
expires_at integer not null,
created_at integer not null
);
create index sessions_expires_at_idx on sessions(expires_at);
You’ll notice there’s no password column and no session_token column anywhere in that schema, because neither raw value should ever touch D1.
Add the password pepper
Each password gets its own random salt, which we store right alongside the hash. On top of that, we add a pepper, a single secret shared across the app and stored outside D1 as an encrypted Worker secret.
Start by generating a random pepper for local development:
openssl rand -base64 32
Drop that value into .dev.vars:
PASSWORD_PEPPER="PASTE_THE_RANDOM_VALUE_HERE"
Make sure .dev.vars* is in your .gitignore so you never commit it. For production, generate a different value and set it through Wrangler:
npx wrangler secret put PASSWORD_PEPPER
Never put the pepper in D1 or wrangler.jsonc. You also need to keep it stable over time, because if you lose it, you won’t be able to verify any existing passwords.
Hash the password
Every password goes through two steps before hitting the database. First, HMAC-SHA256 transforms it using the secret pepper, and then PBKDF2 derives the stored hash using a fresh random salt.
Here’s the core hashing code:
const salt = crypto.getRandomValues(new Uint8Array(16))
const pepperKey = await crypto.subtle.importKey(
'raw',
new TextEncoder().encode(env.PASSWORD_PEPPER),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign'],
)
const pepperedPassword = await crypto.subtle.sign(
'HMAC',
pepperKey,
new TextEncoder().encode(password),
)
const passwordKey = await crypto.subtle.importKey(
'raw',
pepperedPassword,
'PBKDF2',
false,
['deriveBits'],
)
const hash = await crypto.subtle.deriveBits(
{
name: 'PBKDF2',
hash: 'SHA-256',
salt,
iterations: 600_000,
},
passwordKey,
256,
)
Base64url-encode the salt and hash, then join all four values into a single versioned string:
pbkdf2_sha256_peppered$600000$SALT$HASH
Saving the algorithm name and iteration count right inside the string gives you a clean upgrade path later. When you raise the iteration count down the road, a future login can spot an older format, verify it once, and swap in a stronger record.
Validate the password before hashing it
Because password hashing is slow on purpose, reject bad input before spending any CPU time on it.
For password-only logins, require at least 15 characters and allow at least 64. Don’t force users to include one uppercase letter, one number, and one symbol. Those composition rules lead to predictable passwords and make passphrases harder to use.
You should also check new passwords against a blocklist of common and breached values, since length doesn’t help much if the password is already in every attacker’s dictionary. Put a generous cap on the UTF-8 byte length too, and reject anything larger instead of silently truncating it. That limits the work done before PBKDF2 and keeps someone from sending a massive password body to burn through your Worker’s CPU.
Why use both a salt and a pepper?
The salt stops an attacker from reusing the same precomputed password table across every account, while the pepper protects you if only the D1 database leaks. Without the Worker secret as well, a copy of the database alone isn’t enough to start testing guesses.
A pepper still doesn’t replace a strong password hash, though. If both D1 and the Worker secret leak, an attacker can still run an offline attack against those hashes.
OWASP recommends at least 600,000 PBKDF2-HMAC-SHA256 iterations. Don’t weaken your password hash just to fit inside the Free Workers CPU limit. Use Paid Workers with an appropriate CPU budget, or hand auth off to a managed service instead. Benchmark the complete login flow on a deployed Worker to see how it performs, and keep recording the work factor with each hash so you can raise it when the guidance changes.
Verify a password
Since password hashes are one-way, login works by repeating the derivation. Split the stored record, decode its salt and hash, and run the submitted password through the same HMAC and PBKDF2 steps.
Then compare the two fixed-size hashes using Cloudflare’s timing-safe check instead of comparing encoded strings with ===:
const valid = crypto.subtle.timingSafeEqual(
candidateHash,
storedHash,
)
Even when the email doesn’t exist in D1, run one password derivation with a dummy salt and hash before responding. If you skip that step, unknown emails return much faster and reveal which addresses have accounts.
Return the exact same error payload in both cases:
{ "error": "Invalid email or password" }
Make sure the HTTP status code, response size, and rough timing match as well. A generic JSON message doesn’t help if an unknown account returns 404 in 5 ms while a real account returns 401 after the hash finishes.
Rate-limit login attempts before running PBKDF2, using two independent limits: one tied to the account identifier and one tied to a client or network signal. Relying only on IP addresses can block a whole school or office, whereas limiting only by account lets an attacker spread guesses across many addresses. When either limit trips, return a generic 429. If you add increasing delays or temporary lockouts, design them carefully so an attacker can’t permanently lock someone out of their account.
Create a session
After a user registers or logs in, generate 32 random bytes for the session token. Send the raw token to the browser, and store only its SHA-256 hash in D1:
const token = crypto.getRandomValues(new Uint8Array(32))
const tokenHash = await crypto.subtle.digest(
'SHA-256',
token,
)
Base64url-encode the original token before putting it in the cookie, and save the encoded hash in the sessions table along with the user ID and expiry time.
Every successful login should get a fresh token. If your app had an anonymous or pre-authentication session, destroy it instead of upgrading it in place. Issue a new token after any privilege change too, and invalidate other sessions after a password reset unless your product explicitly lets users keep them.
Why is fast SHA-256 enough here when we used slow PBKDF2 for passwords? Humans pick guessable passwords, whereas session tokens contain 256 random bits that we generated ourselves, so an attacker can’t realistically guess them.
Set the session cookie
Send the original token back in a hardened cookie:
Set-Cookie: __Host-session=TOKEN; Path=/; HttpOnly; Secure; SameSite=Lax
Here’s what each attribute does:
HttpOnlystops JavaScript from reading the token.Securesends it only over HTTPS.SameSite=Laxblocks many cross-site requests.Path=/makes it available to the whole application.__Host-prevents a sibling subdomain from replacing it.
Don’t put the session token in localStorage, since browser JavaScript can read it there.
Authenticate a request
For GET /api/me, read the cookie, hash its value, and look up an active session in D1:
select users.id, users.email
from sessions
join users on users.id = sessions.user_id
where sessions.token_hash = ?1
and sessions.expires_at > ?2
If the query returns no row, respond with 401.
Logout runs the same flow in reverse: hash the cookie value, delete that session row, and return an expired cookie. You should also clean up expired sessions periodically, and a daily Cron Trigger is plenty for a small system like this.
Protect state-changing requests
Since the browser sends cookies automatically, we have to handle CSRF ourselves.
For registration, login, and logout, compare the Origin header with the Worker’s origin:
const origin = request.headers.get('Origin')
const expectedOrigin = new URL(request.url).origin
if (origin !== expectedOrigin) {
return new Response('Cross-origin request rejected', { status: 403 })
}
Also accept only application/json, since a normal cross-site HTML form can’t send that content type.
Treat SameSite and the JSON content type as extra layers rather than the complete defense. If your deployment can’t count on a trustworthy Origin or Referer header, use a real CSRF token. You can also reject Sec-Fetch-Site: cross-site before doing any auth work, keeping origin verification as the fallback for clients that don’t send Fetch Metadata headers.
If your frontend and API live on different origins, define an explicit list of trusted origins and never replace that check with *.
Test the flow
Start the Worker locally:
npx wrangler dev
Register a user and save the cookie:
curl -i -c cookies.txt \
-H 'Content-Type: application/json' \
-H 'Origin: http://localhost:8787' \
--data '{"email":"ada@example.com","password":"correct horse battery staple"}' \
http://localhost:8787/api/register
Then send that cookie to the protected endpoint:
curl -i -b cookies.txt http://localhost:8787/api/me
Inspect D1 afterward. You should see a versioned password record and a hashed session token, with neither the plain password nor the raw cookie token stored anywhere.
Before using this in production
What we built here is just the small cryptographic core of an authentication system. A real product also needs:
- email verification
- password reset with short-lived, single-use tokens
- rate limiting by account and client signal
- bot protection where abuse justifies it
- session listing and revocation
- session invalidation after password changes
- safe logging that excludes passwords and tokens
- tests for malformed, expired, and cross-origin requests
Registration and recovery need the same enumeration protection as login. Don’t answer registration with “this email already exists” while an unknown address gets a different response. Return one neutral message like “Check your email to continue.” If the account already exists, send a private notification or sign-in link to its owner instead.
Don’t grant verified-user privileges just because registration inserted a row either. Start with an unverified account state, keep verification tokens short-lived and single-use, and flip that state only after the person proves they control the address.
If you’re building a product that needs all of this right away, my advice is to reach for a well-maintained authentication library instead of maintaining every piece by hand.
Want me to talk about your product? You can sponsor this site.
Related posts about cloudflare: