Next.js Discord

Discord Forum

Implementing Authorization in Next.js + Firebase

Answered
Egyptian Mau posted this in #help-forum
Open in Discord
Egyptian MauOP
I'm building an admin dashboard where I want to restrict the access to dashboard to authenticated and authorized users (admins) only.

I can apply checks in the middleware, for eg., if the route starts with "/dashboard", it will check if the user is authorized or not, and send a 401 HTTP Error.
But the concern here is how do I check for the user? I am using firebase in client side and firebase-admin on server side (middleware and api routes).

Though there is a way. If I can somehow pass the user's "tokenId" (provided by firebase on client side) in the "Authorization" Header of every request, I can use that token to get info about user. It works like a Bearer token.
But how do I pass this "tokenId" into every request if the user is authenticated?
Answered by B33fb0n3
If you want to set the header, you can also access the cookies and set the header for the specific req
View full answer

17 Replies

you can set the token in your cookies and then access the cookies in your backend
Egyptian MauOP
I'm not sure how to do that
The last time I did that was with axios where I just made an axios.instance and pass in the credentials for every request
But how do I do that in this case since it's completely handled by nextjs routing system
Also is it considered a safe option to pass in auth tokens in cookies?
you can get and set your cookies in your backend like [this](https://nextjs.org/docs/app/api-reference/functions/cookies)
Yes, it's secure to safe them inside your cookies
Egyptian MauOP
Oh okay I can set the cookie when logging in and it will persist throughout the session and requests
If I understand it correctly
exactly 👍
Egyptian MauOP
Thank you
By the way I was wondering if it's possible to do the same, just instead of cookies I want to pass in the Authorization header
If not on client side, I can do that on server using an API route too
If you want to set the header, you can also access the cookies and set the header for the specific req
Answer
@Egyptian Mau solved?
@B33fb0n3 <@1174971267825291300> solved?
Egyptian MauOP
Oh yes it is solved I was inactive for a while
Thanks a lot!