-
-
Notifications
You must be signed in to change notification settings - Fork 28
doc: add auth middleware example to examples folder #116
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
WalkthroughA 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
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
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
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.
Example instruction:
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. Comment |
There was a problem hiding this 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 productionUsing 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
📒 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)
| .derive(async ({ cookie: { auth }, jwt }) => { | ||
| const user = await jwt.verify(auth.value) | ||
| if (!user) throw new Error('Unauthorized') | ||
| return { user: user } | ||
| }) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
| .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.
Summary
This PR adds an
auth-middlewareexample to the examples folder. It demonstrates a common pattern familiar to Express users, where averifyJWTmiddleware 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:
This example could serve as the reference snippet for that section.
Summary by CodeRabbit