Skip to content

Refresh: Backend with TypeScript, PostgreSQL & Prisma part 3 β€” Authentication & Authorization (Prisma ORM 7 + Hono)#8003

Merged
nurul3101 merged 4 commits into
mainfrom
blog/refresh-backend-auth-part-3
Jul 3, 2026
Merged

Refresh: Backend with TypeScript, PostgreSQL & Prisma part 3 β€” Authentication & Authorization (Prisma ORM 7 + Hono)#8003
nurul3101 merged 4 commits into
mainfrom
blog/refresh-backend-auth-part-3

Conversation

@vanrensbird

@vanrensbird vanrensbird commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

What

Refreshes part 3 of the series, Authentication & Authz (2020), for Prisma ORM 7. Follows #8000 (part 1) and #8001 (part 2), continuing the migration to Hono.

Key change: auth stack migrated Hapi β†’ Hono

  • Auth strategy β†’ middleware. Hapi's JWT scheme/strategy becomes a single authMiddleware. hapi-auth-jwt2 + jsonwebtoken are replaced by Hono's built-in hono/jwt (sign/verify, HS256), so no extra auth libraries.
  • pre functions β†’ authorization middleware. isRequestedUserOrAdmin, isTeacherOfCourseOrAdmin, and requireAdmin are reusable Hono middlewares, mirroring how the Hapi pre functions read request.auth.credentials.
  • SendGrid β†’ Resend. @sendgrid/mail becomes a small fetch-based sendEmailToken, with a debug fallback that logs the token when RESEND_API_KEY is unset, so the flow works locally with no provider.

Schema changes

  • Added the Token model + TokenType enum, made firstName/lastName optional, added isAdmin.
  • Set onDelete: Cascade on the Tokenβ†’User relation so DELETE /users/{userId} keeps working once users have tokens (a real fix, not cosmetic).
  • No preview-feature flags β€” connectOrCreate, transactions, and aggregates are all stable in Prisma 7. Migrations: add-token, token-cascade.

Other changes

  • Prisma 7 throughout; self-contained continuation of part 2 (no cloning the archived repo).
  • Dropped the livestream framing and YouTube embed (teaches the old stack). Reversible.
  • Concepts prose (authn vs authz, hashing, passwordless, JWT, stateful JWT) kept largely intact.
  • Closing links: Prisma Console, MCP server, Compute (part 4 teaser), Prisma Next.
  • Frontmatter: author (Daniel Norman) and 2020-09-10 date kept; updatedAt: 2026-07-03 drives the visible "Updated" line and JSON-LD dateModified. Meta description updated (Hono).

Testing

  • Built the full auth flow in a fresh Prisma ORM 7.8.0 project (Node 20, ESM) continuing from part 2, against a real Prisma Postgres database.
  • tsc --noEmit clean. vitest run β†’ 11/11 tests pass (status, login+authenticate flow, and authorization: 401 without token, 403 non-admin cross-user, admin override, self CRUD).
  • Live curl: login β†’ token logged β†’ authenticate returns a JWT in the Authorization header β†’ /profile 401 without / 200 with token β†’ a reused email token is correctly rejected (401).
  • pnpm types:check passes; pnpm lint:links clean for this file; all external links 200.

πŸ€– Generated with Claude Code

Summary by CodeRabbit

  • Documentation
    • Updated the authentication tutorial to reflect a newer Prisma ORM and Hono-based approach.
    • Revised the login and verification flow, including email token delivery, API token issuance, and authorization checks.
    • Refreshed setup and migration guidance for the updated tooling and added an update note describing the switch in authentication middleware.

…) for Prisma ORM 7 + Hono

Migrates passwordless email auth + JWT + authorization from Hapi to Hono:
hono/jwt for signing/verifying, an authMiddleware replacing the jwt
strategy, and reusable authorization middlewares (isRequestedUserOrAdmin,
isTeacherOfCourseOrAdmin, requireAdmin) replacing Hapi pre-functions.
SendGrid -> Resend with a debug fallback that logs the token when no key
is set. Adds the Token model + isAdmin with an onDelete: Cascade relation.
Kept author + date; updatedAt 2026-07-03.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@vercel

vercel Bot commented Jul 3, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
blog Ready Ready Preview, Comment Jul 3, 2026 4:05pm
docs Ready Ready Preview, Comment Jul 3, 2026 4:05pm
eclipse Ready Ready Preview, Comment Jul 3, 2026 4:05pm
site Ready Ready Preview, Comment Jul 3, 2026 4:05pm

Request Review

@coderabbitai

coderabbitai Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The tutorial article was updated to describe a Prisma ORM 7 and Hono-based passwordless authentication and authorization flow instead of the prior Hapi-based approach. It also revises the email provider, middleware structure, routes, authorization checks, tests, and closing summary.

Changes

Blog article rewrite

Layer / File(s) Summary
Frontmatter and intro/prerequisites update
apps/blog/content/blog/backend-prisma-typescript-orm-with-postgresql-auth-mngp1ps7kip4/index.mdx
Adds updatedAt metadata and an update note; revises intro/prerequisites to reference Resend and Node.js 20+.
Auth concepts, Prisma model, and email sending
apps/blog/content/blog/backend-prisma-typescript-orm-with-postgresql-auth-mngp1ps7kip4/index.mdx
Refreshes JWT/stateful-token explanation, updates Prisma Token model migration for Prisma ORM 7, and replaces SendGrid email sending with a Resend-based sendEmailToken function.
Hono authMiddleware and typed credentials
apps/blog/content/blog/backend-prisma-typescript-orm-with-postgresql-auth-mngp1ps7kip4/index.mdx
Rewrites Hapi auth strategies into Hono authMiddleware using sign/verify from hono/jwt, validating tokens and setting typed credentials via AppEnv/AuthCredentials.
Login/authenticate routes and app wiring
apps/blog/content/blog/backend-prisma-typescript-orm-with-postgresql-auth-mngp1ps7kip4/index.mdx
Rewrites POST /login and POST /authenticate as Hono routes and updates app wiring to mount open routes before applying authMiddleware.
Authorization middleware for route protection
apps/blog/content/blog/backend-prisma-typescript-orm-with-postgresql-auth-mngp1ps7kip4/index.mdx
Replaces Hapi pre functions with reusable Hono middleware (isRequestedUserOrAdmin, isTeacherOfCourseOrAdmin, requireAdmin) returning 403 on denial.
Test updates and summary section
apps/blog/content/blog/backend-prisma-typescript-orm-with-postgresql-auth-mngp1ps7kip4/index.mdx
Updates tests to use real Prisma users/tokens and signed JWTs instead of Hapi injected credentials, and revises the closing summary to describe the Hono-based architecture.

Estimated code review effort: 4 (Complex) | ~45 minutes

Related PRs: None identified.

Suggested labels: documentation, blog

Suggested reviewers: None identified.

Poem

A rabbit hopped from Hapi's den,
To Hono's fields, JWT in hand,
Resend now carries tokens light,
While Prisma models hold the fight,
Auth middleware guards the gateβ€”
This tutorial's had quite the update! πŸ°πŸ“

πŸš₯ Pre-merge checks | βœ… 5
βœ… Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage βœ… Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check βœ… Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check βœ… Passed Check skipped because no linked issues were found for this pull request.
Description Check βœ… Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check βœ… Passed The title clearly matches the main update: part 3 refreshed for Prisma ORM 7 and Hono-based authentication and authorization.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❀️ Share

Comment @coderabbitai help to get the list of available commands.

@argos-ci

argos-ci Bot commented Jul 3, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Argos notifications β†—οΈŽ

Build Status Details Updated (UTC)
default (Inspect) βœ… No changes detected - Jul 3, 2026, 4:12 PM

'Authz' is engineer shorthand and reads inconsistently next to the
fully-spelled 'Authentication'. Spell it out so the title is clear for
human and agent readers, and matches the metaTitle. Slug and metaTitle
unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@vanrensbird vanrensbird changed the title Refresh: Backend with TypeScript, PostgreSQL & Prisma part 3 β€” Authentication & Authz (Prisma ORM 7 + Hono) Refresh: Backend with TypeScript, PostgreSQL & Prisma part 3 β€” Authentication & Authorization (Prisma ORM 7 + Hono) Jul 3, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

πŸ€– Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@apps/blog/content/blog/backend-prisma-typescript-orm-with-postgresql-auth-mngp1ps7kip4/index.mdx`:
- Line 226: The JWT_SECRET fallback in the blog example is a silent security
footgun because it lets deployments run with a published signing key. Update the
example around JWT_SECRET to fail fast when the environment variable is missing,
especially in production, and remove the default secret fallback so
misconfiguration is surfaced immediately. Use the JWT_SECRET constant and any
startup/config initialization code nearby to enforce this check.
- Around line 238-241: The email token generator currently uses Math.random(),
which is predictable for a credential; update generateEmailToken to use a CSPRNG
via crypto.randomInt(10000000, 100000000) while keeping the result as an 8-digit
string. Make sure the change stays within the existing generateEmailToken
function and preserves the current return format.
πŸͺ„ Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
βš™οΈ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 48596fdd-b5cf-4898-9473-5b8b31d8599d

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 8ba14fb and c7eb740.

πŸ“’ Files selected for processing (1)
  • apps/blog/content/blog/backend-prisma-typescript-orm-with-postgresql-auth-mngp1ps7kip4/index.mdx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants