Skip to content

Commit

Permalink
feat(nextjs): Return 401 Response on protected API routes (#1276)
Browse files Browse the repository at this point in the history
* feat(nextjs): Return 401 Response on protected API routes

This commit introduces a new apiRoutes param on authMiddleware.

If apiRoutes is omitted, then a default heuristic is the following:
If the route path is ['/api/(.*)', '/trpc/(.*)'] or Request has Content-Type: application/json or
Request method is not-GET,OPTIONS,HEAD ,
then this is considered an API route.

* test(nextjs): Fix tests after adding isApiRoute prop to auth object

* chore(nextjs): Add changeset

* fix(nextjs): Change 401 response body to null

* chore(nextjs): Change the description text on apiRoutes prop
  • Loading branch information
anagstef authored Jun 7, 2023
1 parent d7dced5 commit 78c31df
Show file tree
Hide file tree
Showing 6 changed files with 248 additions and 53 deletions.
9 changes: 9 additions & 0 deletions .changeset/seven-mayflies-push.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@clerk/nextjs': minor
---
We tweaked the default `authMiddleware` behavior for protected API routes. An unauthenticated request for a protected API route will no longer return a `307 Redirect` - a `401 Unauthorized` response will be returned instead. An API route is considered a request for which the following rules apply:
- The request url matches the following patterns; `['/api/(.*)', '/trpc/(.*)']`
- Or, the request has `Content-Type: application/json`
- Or, the request method is not one of: `GET`, `OPTIONS` ,` HEAD`
A new `apiRoutes` param has been introduced on `authMiddleware`. It can accept an array of path patterns, `RegexExp` or strings. If `apiRoutes` is passed in explicitly, then it overrides the behavior described above and only the requests matching `apiRoutes` will be considered as API routes requests.
For more technical details, refer to the PR's description.
2 changes: 1 addition & 1 deletion packages/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@
"@types/react-dom": "*",
"expect-type": "^0.15.0",
"jest": "*",
"node-fetch-native": "^0.1.8",
"node-fetch-native": "1.1.1",
"ts-jest": "*",
"typescript": "*"
},
Expand Down
Loading

0 comments on commit 78c31df

Please sign in to comment.