Skip to content

Conversation

@amitanshusahu
Copy link

@amitanshusahu amitanshusahu commented Nov 19, 2025

Summary

This PR adds an auth-middleware example to the examples folder. It demonstrates a common pattern familiar to Express users, where a verifyJWT middleware populates the user in the request context.

Why

Developers migrating from Express often look for equivalent patterns in Elysia, especially around authentication middleware. Having an example in the codebase reduces onboarding friction.

Proposal

Consider adding this in “Migrating from Express” section in the elysiajs documentation as well, highlighting common patterns such as:

  • Auth middleware pattern
  • Adding context to the request
  • Guarding routes

This example could serve as the reference snippet for that section.

Summary by CodeRabbit

  • Documentation
    • Added authentication example featuring JWT-based security with cookie-based token verification, protected routes for authenticated users, and public endpoint demonstrations.

@coderabbitai
Copy link

coderabbitai bot commented Nov 19, 2025

Walkthrough

A new example file introducing JWT-based authentication in Elysia. The setup includes a protected route requiring authentication via JWT cookie verification, a public route without authentication requirements, and a parent application that composes these routes together.

Changes

Cohort / File(s) Summary
Authentication Example
example/auth-plugin.ts
New file demonstrating Elysia JWT authentication plugin configuration with cookie-based token verification, protected route (/me), public route (/public), and route composition.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant PublicRoute as /public
    participant AuthPlugin as Auth Plugin
    participant ProtectedRoute as /me
    
    User->>PublicRoute: GET /public
    PublicRoute-->>User: Response (no auth needed)
    
    User->>AuthPlugin: GET /me (+ JWT cookie)
    AuthPlugin->>AuthPlugin: Verify JWT from cookie
    alt Token Valid
        AuthPlugin->>ProtectedRoute: User object exposed
        ProtectedRoute-->>User: Personalized response
    else Token Invalid
        AuthPlugin-->>User: Unauthorized
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Review JWT plugin configuration for security best practices
  • Verify cookie extraction and token validation logic
  • Confirm protected route implementation correctly uses authenticated user context

Poem

🐰 A token tucked in cookies sweet,
Where users and auth securely meet,
Protected routes now guard the way,
While public paths see light of day! 🔐✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title describes adding an auth middleware example, which matches the actual change of introducing auth-plugin.ts demonstrating JWT authentication in Elysia.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

📝 Customizable high-level summaries are now available in beta!

You can now customize how CodeRabbit generates the high-level summary in your pull requests — including its content, structure, tone, and formatting.

  • Provide your own instructions using the high_level_summary_instructions setting.
  • Format the summary however you like (bullet lists, tables, multi-section layouts, contributor stats, etc.).
  • Use high_level_summary_in_walkthrough to move the summary from the description to the walkthrough section.

Example instruction:

"Divide the high-level summary into five sections:

  1. 📝 Description — Summarize the main change in 50–60 words, explaining what was done.
  2. 📓 References — List relevant issues, discussions, documentation, or related PRs.
  3. 📦 Dependencies & Requirements — Mention any new/updated dependencies, environment variable changes, or configuration updates.
  4. 📊 Contributor Summary — Include a Markdown table showing contributions:
    | Contributor | Lines Added | Lines Removed | Files Changed |
  5. ✔️ Additional Notes — Add any extra reviewer context.
    Keep each section concise (under 200 words) and use bullet or numbered lists for clarity."

Note: This feature is currently in beta for Pro-tier users, and pricing will be announced later.


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 and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
example/auth-plugin.ts (1)

7-12: Avoid hard‑coding JWT secret in example to discourage copy‑paste into production

Using a literal 'top-secret' works for a quick example but is easy to copy into real apps. Since this file is documentation-oriented, it may be safer to model environment-based configuration:

-			name: 'jwt',
-			secret: 'top-secret',
+			name: 'jwt',
+			// In a real app, always load secrets from env/config rather than hard-coding.
+			secret: process.env.JWT_SECRET ?? 'dev-only-secret',

This keeps the example runnable while nudging users toward a production-ready pattern.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c1ef884 and d1d1a93.

📒 Files selected for processing (1)
  • example/auth-plugin.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
example/auth-plugin.ts (1)
src/index.ts (1)
  • jwt (194-390)

Comment on lines +14 to +18
.derive(async ({ cookie: { auth }, jwt }) => {
const user = await jwt.verify(auth.value)
if (!user) throw new Error('Unauthorized')
return { user: user }
})
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Guard against missing auth cookie to avoid runtime errors

If the auth cookie is absent (unauthenticated request or different cookie name), auth will be undefined and auth.value will throw a TypeError before you can treat the request as unauthorized. That will likely surface as a 500 instead of a clean 401-style auth failure.

Consider defensively checking the cookie before verifying the token:

-	.derive(async ({ cookie: { auth }, jwt }) => {
-		const user = await jwt.verify(auth.value)
-		if (!user) throw new Error('Unauthorized')
-		return { user: user }
-	})
+	.derive(async ({ cookie: { auth }, jwt }) => {
+		const token = auth?.value
+
+		if (!token) {
+			throw new Error('Unauthorized')
+		}
+
+		const user = await jwt.verify(token)
+
+		if (!user) {
+			throw new Error('Unauthorized')
+		}
+
+		return { user }
+	})

This keeps the middleware semantics (all failures become “unauthorized”) while avoiding low-level runtime errors from missing cookies.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
.derive(async ({ cookie: { auth }, jwt }) => {
const user = await jwt.verify(auth.value)
if (!user) throw new Error('Unauthorized')
return { user: user }
})
.derive(async ({ cookie: { auth }, jwt }) => {
const token = auth?.value
if (!token) {
throw new Error('Unauthorized')
}
const user = await jwt.verify(token)
if (!user) {
throw new Error('Unauthorized')
}
return { user }
})
🤖 Prompt for AI Agents
In example/auth-plugin.ts around lines 14 to 18, the code assumes cookie.auth
exists and accesses auth.value which can raise a TypeError if the cookie is
missing; update the derive handler to first check that cookie.auth is present
and has a value (e.g., early-throw an Unauthorized error if missing), then call
jwt.verify inside a try/catch (or otherwise handle verification failures) and
throw the same Unauthorized error on any verification or falsy user result so
all failure modes produce a controlled 401-style response instead of a runtime
500.

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.

1 participant