Trying to add refresh token logic in next-auth
Vložit
- čas přidán 9. 09. 2024
- no lie, next-auth kind of sucks
some links to read authjs.dev/gui...
github.com/nex...
My Products
🏗️ WDC StarterKit: wdcstarterkit.com
📖 ProjectPlannerAI: projectplanner...
🤖 IconGeneratorAI: icongeneratora...
📝 ThumbnailCritique: thumbnailcriti...
Useful Links
💬 Discord: / discord
🔔 Newsletter: newsletter.web...
📁 GitHub: github.com/web...
📺 Twitch: / webdevcody
🤖 Website: webdevcody.com
🐦 Twitter: / webdevcody
screw this I'm switching back to database strategy. I'm not convinced using jwt strategy isn't worth the hassle when it comes to using next-auth
just ditch next-auth KEKW
I'm still not sure what the benefits are to JWT but I just swapped to it because I need to support a Credentials to support something like a yubikey and the credentials providers don't support database sessions... though I don't understand why.
I would def use if i wanted credentials based strategy i would use lucia
The benefits of the jwt show case themselves when you have large high traffic systems. As one of the main selling points is that don’t need to go to the db every round trip. Everything is encapsulated in the jwt itself. You should only need to hit to the db if you are nearing expiration and need to refresh it using a long lived token
This very week I had to reimplement our company’s auth because of how bad next-auth v5 is. We went with iron-session and rolled our own, but Lucia auth seems good.
I've found myself shimmying the entire auth logic in the next auth config. To the point that It would've been easier to roll my own auth from scratch .. that's next auth for you
Try Lucia auth 😅
Same here. Next auth is just unnecessarily complicated. I would’ve been better off writing my own auth from scratch 😂
When I first used next-auth, I hated it because of these reasons. I was wondering how everyone is advertising next-auth as a good solution. I am glad I am not the only one who thinks so.
This video actually give me better understanding about the refresh token thing. One thing I notice, if with db session we do query our db more frequently. But also if we use jwt and store refresh token on db and check every 5 minutes. I do thing its just easier to use the db session instead.
I tried using next auth at first and absolutely hated it. Could not get it to consistently refresh tokens across sever components, server actions, client components, etc. As i have a separate backend i switched it up where the backend handles the oauth flow and refreshes tokens automatically. All I need the frontend to do is check the cookie exists. If next Middleware doesn't see the cookie or a fetch returns 401 the user hits the backend /login route. You could almost certainly set that up with route handlers too I imagine.
Cool, I’ll have to dig into next auth again. I tested the v5 beta a few months ago and kept running into various issues. So switched back to Clerk. I do like next auth, but just didn’t have time to mess with authentication because it is always more of a distraction from what I actually wanted to build. Looking forward to seeing how your project turns out and I’ll revisit next auth again soon.
Can’t Beat clerk at this point
Yes, you can’t beat a 5 minute setup. Weird though, have you noticed in your other Clerk projects that Clerk switches static rendered pages to dynamic render? More weird, when I take that same project and tie into Convex with the convex clerk provider the static render pages switch back to static as were originally were. Maybe it’s always been this way, but thought it might just be the new Clerk update.
@@Stallion45 I’m not sure, but if you ever access the user session on any page or in a layout for a header, everything needs to become dynamic because it needs to read cookies
That’s what I was thinking, so I built two scratch apps with no content or authentication. Just the default next 14 and the clerk provider pass through. Must be something breaking static renders in the Clerk provider, but not the clerk provider with convex component.
How I would like to do it.
/auth/login - issue refresh token and acesss token
Store refresh token in cookie and don't store access token at all.
/auth/refresh - get new access token using, called on full page reload or if token expire on when client is still on the page.
Reduce lifetime of acess token to
Great vid! I love these forms of videos, my favourite! :)
I suppose a way for users to "take back" control when they get their access token/refresh token taken could be to just logout and log back in, would it make sense to delete old refresh tokens when you login? That's how the typical cookie system works right, you're only vulnerable until you login again
It gets tricky if you want to support a user logged in on multiple devices because you can’t just delete all old refresh tokens because it’ll log you out of other devices. The best way is you need a way to track each session separate after login with its own refresh token. Also you’re supposed to delete the refresh token after it’s used and make a new ones
@@WebDevCody oh I see yeah, forgot about that. Makes it a lot more tricky! Are the JWT tokens the same JSON web tokens that are used for APIs? I didn’t realise they were also used for typical user sessions, that’s cool.
I’d love to see more of these though, it’s really insightful, keep it up!
My approach was to fetch a new token from the oauth provider when it expires then replace the old one, IDK if this the right way but I saw the same method in the docs.
Nice one! Thanks for sharing this with us, it's a great one 👏
I'm doing a test project right now and all I wanted to do was have the ability to deauthorize (ban) a user by changing their role in real time. I'm using credentials provider and I was told that using a refresh token was probably the best way, because in my current setup I'm querying the database and getting the user's role from there on every request to a protected page (which is not scalable at all obviously). After hitting my head against the wall for 3 days I genuinely think querying the database on every request and just making read replicas would be EASIER and more convinient than implementing a proper way to invalidate in authJS. Just horrific documentation especially for a new dev like myself.
I’d say unless you’re at the scale you think you need, a db lookup to get the session works fine. Honestly just rolling your own auth might be faster than the time it’ll take to hack a solution into next auth.
hello, how do you handle when a refresh token is invalid, I mean in my case I store it in my database and check if it's present, if not I'd like to clear session but I can't find how to achieve it
The best way to achieve this is by using redis, and refresh the token on the next-auth session callback. If you want to see an exemple, let me know !
I've decided to just drop next-auth at this point. I don't like the library, documentation, or maintainer.
You should check into building your own auth (cognito being the easiest for me) because it gives you way more control with less code. You already know the basics by now so you'll find it much simpler.
Great job bubby!!!! ❤
Why "jwt" over "database"? I can see that database is present in the project. As I am working on project of my own and I went with "database" strategy I wonder if there are tradeoffs I am not aware of?
with database, you do a query against your database every single time you call useSession or getServerSession. With JWT you can add claims to the token directly which reduces the unnecessary database queries.
If you're using jwt, curious on why store it in the database? Because this becomes the database strategy.
Cuz in jwt, there's a private signing key which encrypts and decrypts the token stored in http only cookie (no uuid but hash functions used). No database involved. So this code will become much simpler.
I’m storing the refresh token in the database, not the jwt. Storing the refresh token gives you a way to invalid it the access token from being able to refresh
I love Next Auth but it is a constant pain when you run into basic things it doesn't support still
I have a problem with the minecraft server hosting project I am trying to practice but when I run the agent it gives me an error and I can only run the client please help thanks
I dont think you should add properties to a jwt token, because you cant invalidate a token, so once you say X token can do Y, you cant aftwards say that token X cant do Y anymore
That’s why tokens should be short lived for only 5-10 minutes. If revoking permissions to something should be instant, then yes you should check the user role from the database on every request
hello sir, sorry my english is bad. I want to ask, I have followed your tutorial about auth js rotation. but why in my code does the refresh token only run once, then it refreshes the token with a long refresh token, even though in auth.ts I have equated the algorithm according to your video. btw, the application I'm working on is next js. If you reply to my message, I will send some code so that you can give me a solution.
Hey Cody just wondering why you are saving refresh token in db, i understood your point for security but couldnt you just encrypt it with a secret on backend ? and put it in httponly cookie? incase of compromise you could just change the secret salt, (this might lead to many other people getting logged out though, but its a very rare case to happen)
That’s just the common convention many do. Logging everyone out because one key got leaked is enough of an issue to warrant saving each token as a separate revokable thing in a db
I'm new to Nextjs and I'm trying to implement access/refresh token logic but without JWT. My API is in Go. Does next-auth support that? From what I understood reading the docs, it only supports JWT. Is that correct?
Idk at this point
@@WebDevCody It's ok. Thanks for the reply though.
next and next-auth is a joke, you can use it only for hello world projects. in real world scenario where you need to support auth calls to api both in browser and server its impossible to implement this in next. switched to remix and feeling good
This is a skill issue bud.
@@cybor-gg Was just referring to how nickolay has changed framework because of the issues he's been having. I've kept out new upcoming auth tools for some time, lucia for instance. Not a clue, so not going to be much value to you.
Clerk has been my goto for about a year and working just fine, have you looked at that?
you can blacklist your jwt in redis thereby invalidating it
Yeah but then you need to lookup the jwt every api call. That kind of defeats the purpose of using a jwt right?
@@WebDevCody yeeah, but as far as i know this is the only option. at least redis is fast
I haven't used next auth since the pages router. I hope it got easier to customize because back then it always felt gross.
it is still gross imo
@@WebDevCody can u recommend anything else? have u been using lucia for example?
which theme is that ?
Please make a video on Lucia Auth 👀
👏👏
Do you write tests for frontend code
for utility functions yet, but I don't test components. I'd use cypress or playwright to verify the UI
Yuhhhhhhhhh exactly the mf issue I'm dealing with fr
Bro it's way past time for you to move to Remix
If remix had rsc and server actions I would
@@WebDevCody they just showed off RSC today