Skip to content

Commit

Permalink
chore(express): Update playground to use correct error handlers (#4167)
Browse files Browse the repository at this point in the history
  • Loading branch information
wobsoriano authored Sep 13, 2024
1 parent 9ccea9b commit 4a9f6d8
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 12 deletions.
2 changes: 2 additions & 0 deletions .changeset/stale-teachers-greet.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
2 changes: 1 addition & 1 deletion playground/express/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"@clerk/types": "file:.yalc/@clerk/types",
"dotenv": "^16.0.3",
"ejs": "^3.1.6",
"express": "^4.18.2",
"express": "^4.21.0",
"ts-node": "^10.9.1"
},
"devDependencies": {
Expand Down
38 changes: 27 additions & 11 deletions playground/express/src/routes/private.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,39 @@
import type { Response } from 'express';

import { getAuth, requireAuth } from '@clerk/express';
import { Router, Request as ExpressRequest } from 'express';
import { getAuth, requireAuth, UnauthorizedError, ForbiddenError } from '@clerk/express';
import {
Router,
Request as ExpressRequest,
Response as ExpressResponse,
NextFunction
} from 'express';

const router = Router();

router.use(requireAuth);

router.get('/me', async (req: ExpressRequest, reply: Response) => {
return reply.json({ auth: getAuth(req) });
router.get('/me', async (req: ExpressRequest, res: ExpressResponse) => {
return res.json({ auth: getAuth(req) });
});

router.get('/private', async (req, reply: Response) => {
router.get('/admin-only', async (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => {
const auth = getAuth(req);
if (!auth.userId) {
return reply.status(403).end();

if (!auth.has({ role: 'admin' })) {
return next(new ForbiddenError());
}

return reply.json({ hello: 'world', auth });
});
return res.json({ message: 'Hello admin!', auth });
})

router.use((err: Error, _req: ExpressRequest, res: ExpressResponse, next: NextFunction) => {
if (err instanceof UnauthorizedError) {
return res.status(401).json({ error: 'Unauthorized' });
}

if (err instanceof ForbiddenError) {
return res.status(403).json({ error: 'Forbidden' });
}

return next(err)
})

export const privateRoutes = router;

0 comments on commit 4a9f6d8

Please sign in to comment.