I built auth from scratch. Then I deleted it.
JWTs on 7 June, hand-written Google OAuth on 22 June, all of it replaced by Better Auth on 24 June. What I learned building it, and why I deleted it.
A few months ago, I thought building authentication from scratch would help me understand how it all works. So I did it, in MyJournalApp. The git history tells the story better than I can:
- 7 June: "jwt token introduced", and the same day, "jwt bug fix".
- 22 June: "Auth 2.0", hand-written Google login.
- 24 June: "replaced custom auth with better auth".
Version 1: passwords and JWTs
I hashed passwords with bcrypt, signed JWTs, set them as cookies, wrote middleware to verify them, and handled session validation myself. The middleware looked for the token in a cookie first and fell back to a Bearer header:
function auth(req, res, next) {
let token = req.cookies?.jwt
if (!token) {
const authHeader = req.headers.authorization
if (authHeader && authHeader.startsWith('Bearer ')) {
token = authHeader.split(' ')[1]
}
}
if (!token) return next(new AppError('Missing or malformed token', 401))
try {
const payload = verify(token)
req.userId = payload.userId
next()
} catch (err) {
return next(new AppError('Invalid or expired token', 401))
}
}It was a great learning experience. I understood exactly what a session is, what a cookie flag does, and why tokens expire.
Version 2: then I added Google login
That's when I realised authentication is much more than passwords and tokens. Doing OAuth properly by hand means:
- 1Generate a random
statevalue and store it in a short-lived cookie. - 2Redirect the user to Google with your client ID, redirect URI, scopes and that state.
- 3When Google redirects back, check the returned state against the cookie. This is the anti-forgery check that stops CSRF on the login flow.
- 4Exchange the authorization code for tokens, server to server.
- 5Use the access token to fetch the user's profile.
- 6Find or create the local user, sign your own JWT, set the cookie and redirect.
async function googleCallback(req, res) {
const { code, state } = req.query
const savedState = req.cookies?.oauth_state
if (!state || !savedState || state !== savedState) {
throw new AppError('Invalid state parameter (anti-forgery check failed)', 400)
}
// Exchange auth code for tokens
const tokenRes = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ code, client_id, client_secret, redirect_uri, grant_type: 'authorization_code' }),
})
const tokens = await tokenRes.json()
// Get user profile details
const userRes = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
headers: { Authorization: `Bearer ${tokens.access_token}` },
})
const googleUser = await userRes.json()
const user = await authService.findOrCreateGoogleUser(googleUser.sub, googleUser.email)
res.cookie('jwt', sign({ userId: user.id }), cookieOptions)
// ...redirect to the frontend
}Every one of those steps has edge cases: missing codes, failed exchanges, accounts without an email, cookie flags that behave differently in development and production. And that was just one provider. At some point I stopped and asked myself:
“Am I building an app, or am I building an authentication library?”
Version 3: Better Auth
Two days after writing Google OAuth by hand, I replaced all of it with Better Auth. Within a few hours, most of the code I had spent days writing was gone. The whole auth middleware became one call:
async function authMiddleware(req, res, next) {
try {
const session = await auth.api.getSession({ headers: req.headers })
if (!session || !session.user) {
return next(new AppError('Unauthorized: Missing or invalid session', 401))
}
req.userId = session.user.id
req.session = session
next()
} catch (err) {
return next(new AppError('Unauthorized: Session verification failed', 401))
}
}In that one commit, the auth controller went from 149 lines removed to 11 lines added, and the JWT service file was deleted entirely. Here is what changed:
- Passwords: no more manual
bcrypt.hash()and salt rounds. Better Auth handles hashing. - Sessions: instead of signed JWTs, sessions are stored in MongoDB with automatic expiry, so they can actually be revoked.
- Cookies:
HttpOnly,SameSiteand secure flags are configured once, centrally. - Google login: zero custom redirect code. It is just
socialProviders.googlein the config. - Frontend: no more polling
/mein auseEffect. A reactiveuseSession()hook keeps state in sync across tabs.
The biggest win wasn't writing less code. It was being able to focus on the actual product instead of reinventing infrastructure. (Though I'll admit, watching the line count go down gives its own kind of satisfaction.)
Sometimes the best code you write is the code you delete.
I don't regret building it by hand first. Because I had written the state check and the token exchange myself, I knew exactly what Better Auth was doing for me, and what to look at when something went wrong.
Postscript: libraries have edges too
Which is exactly what happened during my internship at Tezi App. I hit an issue where userMap kept coming back as null, which forced us to fetch the user manually with getCurrentUser(). Instead of patching around it, I traced it to the root:
- Our custom Orchid ORM adapter returned an integer (the number of affected rows) instead of an object.
- That value was passed into Better Auth's core logic.
- Better Auth is designed to return
{ status: true }regardless of what the adapter sends. - Because of that abstraction, the real user object never made it through, so
userMapwasnull.
We could have written a custom hook to inject the user object into the flow, but for this case that felt like over-engineering. A single getCurrentUser() call solves it cleanly.
Understanding why mattered more than the one-line fix. Handing auth to a library is the right call, as long as you still know what it's doing underneath.