Skip to content
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

WithMiddlewareAuthRequired should return 401 for /api routes #909

Merged
merged 1 commit into from
Nov 16, 2022

Conversation

adamjmcgrath
Copy link
Contributor

📋 Changes

/api routes protected by withMiddlewareAuthRequired should respond with a 401 for unauthenticated routes (currently it just expects UI pages so only responds with temporary redirects to the login page)

Since middleware can't respond with a body - the recommended way to do this in Next.js middleware is to create a stub api route and rewrite to that

📎 References

https://nextjs.org/docs/messages/returning-response-body-in-middleware
fixes #903

🎯 Testing

$ npm run start:kitchen-sink
$ curl -I http://localhost:3000/api/hello-world-mw
HTTP/1.1 401 Unauthorized

@adamjmcgrath adamjmcgrath added the review:small Small review label Nov 15, 2022
@adamjmcgrath adamjmcgrath requested a review from a team as a code owner November 15, 2022 16:48
@vercel
Copy link

vercel bot commented Nov 15, 2022

The latest updates on your projects. Learn more about Vercel for Git ↗︎

1 Ignored Deployment
Name Status Preview Updated
nextjs-auth0 ⬜️ Ignored (Inspect) Nov 15, 2022 at 4:48PM (UTC)

@Nargonath
Copy link

Thanks for the PR @adamjmcgrath. Shouldn't we update the documentation (README.md and EXAMPLES.MD) to mention that feature?

@adamjmcgrath
Copy link
Contributor Author

Thanks @Nargonath - I think the existing docs explain it pretty well - my expectation would be that "pages" in that context would include pages/api as well. I am however going to take another pass through the README before we release the Beta

@adamjmcgrath adamjmcgrath merged commit 8fb6bde into vNext Nov 16, 2022
@adamjmcgrath adamjmcgrath deleted the mw-for-api-routes branch November 16, 2022 08:59
@Nargonath
Copy link

The reason I mentioned the documentation is that from what I saw in the code it seems you give the ability to the user to override the path used to redirect API requests to the 401 API endpoint. I believe this is undocumented but perhaps I missed it.

@adamjmcgrath
Copy link
Contributor Author

👍 yep, good point. I'm going to add some examples for your use case and will add docs for customising that path

@Nargonath
Copy link

Alright, thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
review:small Small review
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants