Skip to content

Auth Middleware (JWT Guard for Protected Routes) #8

Description

@codebestia

Background

All merchant-facing endpoints (dashboard, invoices, profile, API keys) must require a valid JWT. This middleware needs to be reusable, attach the resolved merchant to req, and return clear errors for missing, malformed, or expired tokens.

Proposed Steps

  1. Create src/middleware/auth.middleware.ts
  2. Extract the Bearer token from the Authorization header
  3. Verify and decode the JWT using JWT_SECRET
  4. Load the Merchant record from the database using sub from the token
  5. Attach it to req.merchant (extend Request type in src/types/express.d.ts)
  6. Call next() on success; return 401 on any failure
  7. Apply the middleware to all /api/v1/merchants/*, /api/v1/invoices/*, and future protected route groups

Acceptance Criteria

  • Request with valid JWT → req.merchant is populated and next() is called
  • Missing Authorization header → 401 { error: "Authentication required" }
  • Malformed or expired JWT → 401 { error: "Invalid or expired token" }
  • Valid JWT but merchant deleted from DB → 401
  • Middleware is applied at the router level (not per-route) for all protected groups
  • TypeScript types are extended so req.merchant is typed as Merchant throughout the codebase

Metadata

Metadata

Assignees

Type

No type

Fields

No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions