After implementing all the code shown in the video I am getting this error: *You're using a Node.js module (crypto) which is not supported in the Edge Runtime.*
in _middlewar.js file am tying to us useSelector hook to get Redux state values ,then I got the error "Invalid hook call. Hooks can only be called inside of the body of a function component............ ". What can I do now..?
Hello, your tutorial is so good. I follow your tutorial but i got error 'Uncaught Error: The edge runtime does not support Node.js 'buffer' module' in middleware.js which is lead to import { verify } from "jsonwetoken" include buffer node.js api. How can i solve that
sadly the jsonwebtoken isn´t able to run on the edge, so this isnt working anymore.. -> you can use "jose" instead -> middleware must be a sibling of "/pages"
this is what im lookin for thanks🚀 I have jwt http-only cookie auth react app too.. and now I want to create another one with next but Im confuse how to role based protected routes in next
First of all, thank you for a great explanation. As a beginner, I have a few issues on my mind. How do I pass the logged in user's information to the next route? Is it a safe choice for me to host user id in jwt? Does it affect the performance that we are checking jwt over middleware every time? I will be glad if you can inform
I created an array of protected routes and checked the JWT only "if (protectedRoutes.includes(pathname))". That way you don't do it every single time. Unfortunately, I didn't find a solution on how to pass the user info to the next stage. I'm decoding it again there, but I don't think it's an expensive operation. Hope this helps.
Thank you for the tutorial its helping me with a project, i have a question, can i access the cookie to grab information? like the user name of the loged user to use for example in a dashboard to show his name?
Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Middleware pages/_middleware When I used middleware in nextjs.... woked fine but build failed.... plz let me get help if possible? Thanks For Great Tutorial.
Realized that after a while. That just doesn’t work. Still looking for the solution. Using next-connect and write the middleware with regular node.js sintax or using next-auth are my guesses.
Does it mean we have to write this code on every api route we want to protect? Isn’t there a central place where we can put this code so nextjs automatically triggers it for all the routes we want to protect? Seems like a bit redundant to me.
Thank you for making this amazing course man! I just have a question. I make a request to the login API and I receive the refresh token that is in the cookie and the access token that is in the response body. Now how should I handle the access token on the client side(next js)? If I store this in a global state like context API, then I don't have access to that state in the getServerSideProps function, and I can't set it in the request.header.authorization because getServerSideProps run on server side!
You don't touch or handle the token on your side. Make a route for example '/me' in which you will get your user's data. Then place that date inside the context and you will know that you have authenticated the user. The request for '/me' is always sent at the beginning of the mount process.
In this example every route under "dashboard" is protected. So if there's "/dashboard/user" or "/dashboard/messages" it will be protected. If you for example just want "/user" and "/messages" to be protected, just check if the url is "messages' or url is "user" and then check the jwt.
Good tutorial, but I have a question. How does the verify method know, that it is a valid JWT? With what it compares? And is it possible to use the verify method if you receive JWT from outside ( you get it from loging in) ?
Hey, thank you. It takes the token that we sent as the first argument, and the secret key that we used on it when we called the "sign" function as the second. It knows because the secret key is the same as the one we signed the token with, because of that it can give you the payload of the token. You can use verify with whatever you want. Someone can place a jwt inside the body or headers of a request, you can still extract it from there and call verify. You can check out their docs here: self-issued.info/docs/draft-ietf-oauth-json-web-token.html
@@tenacity_dev since middle ware came out everyone uses it to protect api routes you are the only tutorial that actually did protected routes, small subscribes now but I'm sure that will change soon
Is there a way to clear cookies and redirect at the same time? I was only able to do one of them by returning either NextResponse.next() or NextResponse.rewrite() (new redirect) but not both.
Hi... it's such as great video. I use the same way as you but I try to make a little modification. I call an API for cookie verification instead of directly do it inside middleware but I can't get the cookie on API Auth. It's always undefined in the log. In other hand, API can get the cookie when I call API Auth from HOC. Do you know about it? Anyway I have separate project for the API. I don't use API of NextJS. Thanks a lot.
Try console.log the cookie and see what does it give. I have a slight same problem a while back when I'm trying to retrieve the token from cookie and it cant be verified as it returns undefined after passing the verify block. So I tried logging it in the console and found out that it returns token=abcd instead of abcd when retrieving it from cookie.
You're not decoding it in the frontend, the _middleware.js file is a middleware. getServerSideProps and getStaticProps are also not on the frontend but you write them like they are.
Check if your env variables are good. You can also solve this problem by calling next(); when you see a token and then verify the token with getServerSideProps function. middleware.js { check for token if i have a token call NextResponse.next() function if i don't have a token call NextResponse.redirect() function } then let's say you went to '/dashboard/user' { export async function getServerSideProps(context) { check for token here verify it if token is alright return the page if it isn't alright return unauthorized } } I made a mistake in the video by not saying that .env variables won't work in _middleware.js in production mode, but you can fix it with the way i gave you
The tutorial is good, specially the previous video but unfortunately I'm getting the following error: Error: URLs is malformed. Please use only absolute URLs - Documentation is saying that we should use NextRequest, clone the url and then rewrite it. I'll try to fix this
thanks for this great tutorial. but i have an issue on getting the cookies back. after i made the middleware, it always return "undefined" for the jwt cookies. also i try to hit /api/user with postman the cookies return undefined. anybody know why this is happening?
Hey man this is quite misleading. The routes are not protected. Only the pages in /dashboard are protected, in other words, only the client-side pages are protected. You need to verify the jwt in the api folder.
Yes of course token should also be verified when a request is sent, but that is kind of common thing done by everyone and i don't think i need to explain that. This video's focus is using the _middleware file. I already said it in the video i think, i'm not doing the full app, i'm just explaining concepts and ideas on how you can build things.
@@idavidgeo They can call next() when they see a token, and then verify it with getServerSideProps then. It's a pretty simple solution on how to verify it if they can't do it in _middleware.js file.
FIXING Node.js module (crypto) which is not supported in the Edge Runtime ERROR: Install jose (used instead of { verify } from jsonwebtoken, it doesnt work anymore) In _middleware: import * as jose from "jose"; Replace his try with: try { console.log("trying to verify jwt"); const verifying = await jose .jwtVerify(jwt, new TextEncoder().encode(`${secret}`)) console.log("verifying", verifying); return NextResponse.next(); }
Thanks bro. I encountered with this error now, how did you manage to fix it? I downgraded the version from 4.8.3 to 4.7.0, but still not working. I'm getting this response: { [JWSInvalid: Compact JWS must be a string or Uint8Array] code: 'ERR_JWS_INVALID', name: 'JWSInvalid' }
@@hectorsum8102 Hey man, never got that error, make sure you use TextEncoder().encode(`${secret}`)) and make sure your secret is a valid string. Make a temp variable for the secret (e.g. let temp = "hello" and use that in place of secret in TextEncoder().encode(`${temp}`)) and see if it works, and narrow it down from there.
@@CemretheFangirl *jwt-decode* is a small library and can only decode, can't validate JWT. Whereas if you have the secret, you will be able to validate the JWT using *jose* .
Thank you for good explanation. One thing - you don’t have to import React from “react” in NextJS pages.
After implementing all the code shown in the video I am getting this error:
*You're using a Node.js module (crypto) which is not supported in the Edge Runtime.*
Great video!
Not sure how I missed in a few days ago when I saw the previous video.
Your videos are on point my friend!
Keep up the great work.
Thank you, it means a lot!
Great tutorial. I have been looking for this for so long. Thanks
Simple and to the point . Respect 💯
So good tutorial to the point not necessaritly long. and clear
This is amazing. Keep up the good work 🙂
Hey thanks a lot for this 👍. Straight to the point and well explained 👌
Great content bro, you explain things so good and easy. Thanks man.
Thank you. Great tutorial and simple explanation
This video deservers more view and likes. Great content
Thank you!
in _middlewar.js file am tying to us useSelector hook to get Redux state values ,then I got the error "Invalid hook call. Hooks can only be called inside of the body of a function component............ ". What can I do now..?
Quick and simple video. Good job 👏
Hello, your tutorial is so good. I follow your tutorial but i got error 'Uncaught Error: The edge runtime does not support Node.js 'buffer' module' in middleware.js which is lead to import { verify } from "jsonwetoken" include buffer node.js api. How can i solve that
Do you find the solution?
Hello,_middleware.js is not working in version 120.4 in nextJS?..is it not supported?
sadly the jsonwebtoken isn´t able to run on the edge, so this isnt working anymore..
-> you can use "jose" instead
-> middleware must be a sibling of "/pages"
This was so great! 😃You really made the whole thing simple.
Thank you!
this is what im lookin for thanks🚀 I have jwt http-only cookie auth react app too.. and now I want to create another one with next but Im confuse how to role based protected routes in next
what a great video it was, just search and get understand everything. Thanks
Allright, you are awesome
Thanks a lot for this video, helped me set up my _middleware properly.
First of all, thank you for a great explanation.
As a beginner, I have a few issues on my mind. How do I pass the logged in user's information to the next route? Is it a safe choice for me to host user id in jwt? Does it affect the performance that we are checking jwt over middleware every time? I will be glad if you can inform
I created an array of protected routes and checked the JWT only "if (protectedRoutes.includes(pathname))". That way you don't do it every single time.
Unfortunately, I didn't find a solution on how to pass the user info to the next stage. I'm decoding it again there, but I don't think it's an expensive operation.
Hope this helps.
@@MarcelPirosca Thank you for your answer and help. For now, I solved the solution with getSession logic. I will try the method you said
You can use the Context API
Thank you for the tutorial its helping me with a project, i have a question, can i access the cookie to grab information? like the user name of the loged user to use for example in a dashboard to show his name?
this is an updated tutorial about this topic ruclips.net/video/zBbqrcvdJjQ/видео.html
Great content, learnt a thing or 2… please can you make a tutorial on deploying a nextjs application? Especially deploying on custom server
Thank you, I'll keep it in mind for my next video.
It was working with next.js 12.0.8 but not working with 12.1.6
Does anybody facing this problem with new version ?
thank you so much SIR,,It helps a lot..❤️❤️
Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Middleware pages/_middleware
When I used middleware in nextjs.... woked fine
but build failed....
plz let me get help if possible?
Thanks For Great Tutorial.
Use this library to verify your token @tsndr/cloudflare-worker-jwt
Realized that after a while. That just doesn’t work. Still looking for the solution. Using next-connect and write the middleware with regular node.js sintax or using next-auth are my guesses.
Does it mean we have to write this code on every api route we want to protect? Isn’t there a central place where we can put this code so nextjs automatically triggers it for all the routes we want to protect? Seems like a bit redundant to me.
Oh, man! It is a middleware that triggers on every request. It then checks if the URL includes the path you want to protect.
It is useful. Thank you.
Glad it was helpful!
There is a new update and I don't think JWT works this way with the new middleware logic. Please, could you make a new video to show the usage?
Thank you for making this amazing course man!
I just have a question.
I make a request to the login API and I receive the refresh token that is in the cookie and the access token that is in the response body. Now how should I handle the access token on the client side(next js)? If I store this in a global state like context API, then I don't have access to that state in the getServerSideProps function, and I can't set it in the request.header.authorization because getServerSideProps run on server side!
You don't touch or handle the token on your side. Make a route for example '/me' in which you will get your user's data. Then place that date inside the context and you will know that you have authenticated the user. The request for '/me' is always sent at the beginning of the mount process.
Does it work with Static Export if I make API Request to my backend express server to check if user can access this page?
Best authentication in next js video
Thank again for a nice tutorial... I have a question... What if i have multiple route to protect...
In this example every route under "dashboard" is protected. So if there's "/dashboard/user" or "/dashboard/messages" it will be protected.
If you for example just want "/user" and "/messages" to be protected, just check if the url is "messages' or url is "user" and then check the jwt.
@@tenacity_dev thanks i test it's work perfectly work... ❤️❤️
i think they changed the _middleware to middleware ?
please verify to me because the both dont work with me
you made it look soo simple
great work! you just got new subscriber 🎉
Good tutorial, but I have a question. How does the verify method know, that it is a valid JWT? With what it compares? And is it possible to use the verify method if you receive JWT from outside ( you get it from loging in) ?
Hey, thank you. It takes the token that we sent as the first argument, and the secret key that we used on it when we called the "sign" function as the second. It knows because the secret key is the same as the one we signed the token with, because of that it can give you the payload of the token.
You can use verify with whatever you want. Someone can place a jwt inside the body or headers of a request, you can still extract it from there and call verify.
You can check out their docs here: self-issued.info/docs/draft-ietf-oauth-json-web-token.html
when i enter at mobile it doesn't work the route protected
how do you automaticly log the user back when the user refreshes the page via jwt?
nice tutorial , but i keep getting cannot resolve module crypto error, any help would be appreciated
Install crypto module if you don't have it. That might resolve the issue.
@@tenacity_dev no it says that crypto module is not allowed in edge runtime functions
@@hitenjain4688 same. You find any solution?
what if i have stored the token in LocalStorage?
but using localstorage you won't be able to do server side rendenring
Excellent!
Glad you liked it!
and how i can pass the payload to the next route or save it in somewhere to access from the next route
hello thanks for your video, can you show us with the new middleware of nextJS ? i am struggling to verify my token now
can i use this logic in my project?
Great work Jonas, could you please make one video that is for custom login form
Hello, please how would I get used data in the client side like logged in users name and all if I can't access cookie and get token
You will send a request to get the users data each time you reload the page and then you can do whatever you want with the user data response.
@@tenacity_dev OK thanks alot
@@tenacity_dev since middle ware came out everyone uses it to protect api routes you are the only tutorial that actually did protected routes, small subscribes now but I'm sure that will change soon
Is there a way to clear cookies and redirect at the same time? I was only able to do one of them by returning either NextResponse.next() or NextResponse.rewrite() (new redirect) but not both.
in auth folder you did't show the login file plz show that file
Hi... it's such as great video.
I use the same way as you but I try to make a little modification. I call an API for cookie verification instead of directly do it inside middleware but I can't get the cookie on API Auth. It's always undefined in the log. In other hand, API can get the cookie when I call API Auth from HOC. Do you know about it?
Anyway I have separate project for the API. I don't use API of NextJS. Thanks a lot.
Try console.log the cookie and see what does it give.
I have a slight same problem a while back when I'm trying to retrieve the token from cookie and it cant be verified as it returns undefined after passing the verify block. So I tried logging it in the console and found out that it returns token=abcd instead of abcd when retrieving it from cookie.
can you please provide full code for this ?????
this was helpful, thanks!
thanks for saving my day
ICAN DECODE TOKEN IN NEXT JS (front)AND RETRIVE INFORMATION OR NOT
?
You're not decoding it in the frontend, the _middleware.js file is a middleware. getServerSideProps and getStaticProps are also not on the frontend but you write them like they are.
bro, when deployed the vercel he is not working ?plz help me about this
Check if your env variables are good. You can also solve this problem by calling next(); when you see a token and then verify the token with getServerSideProps function.
middleware.js
{
check for token
if i have a token
call NextResponse.next() function
if i don't have a token
call NextResponse.redirect() function
}
then let's say you went to '/dashboard/user'
{
export async function getServerSideProps(context) {
check for token here
verify it
if token is alright
return the page
if it isn't alright
return unauthorized
}
}
I made a mistake in the video by not saying that .env variables won't work in _middleware.js in production mode, but you can fix it with the way i gave you
broo, nice video. but you need to update your repo. thanks
Tks bro !
You're Welcome 👍
Thank you so much!
I have a typeError says url.includes is not a function please help me
Check if you got the request object correctly. Url is a property of the request object (req).
Tks sir :)
You're welcome!
The tutorial is good, specially the previous video but unfortunately I'm getting the following error: Error: URLs is malformed. Please use only absolute URLs - Documentation is saying that we should use NextRequest, clone the url and then rewrite it. I'll try to fix this
did you figure it out how to do it? :(
const { pathname, origin } = req.nextUrl
return NextResponse.rewrite(`${origin}/login`).
A better solution, i think is use:
return NextResponse.redirect(new URL('/', req.url))
@@aquilesburlamaqui i also did it
i got this : Error: The edge runtime does not support Node.js 'buffer' module.
Same. Were you able to resolve it?
@@raghavrajaraman5845 nah
Top bro 🤗♥️
How to protect route in next js 13?
I'll make a video about it for next.js 13 using the app directory.
thanks for this great tutorial.
but i have an issue on getting the cookies back.
after i made the middleware, it always return "undefined" for the jwt cookies.
also i try to hit /api/user with postman the cookies return undefined.
anybody know why this is happening?
Do you have a solution for this problem?
@@dinahsaurrr_ yess,
using getServerSideProps and passing (context)
get the jwt cookies from context.req.headers.cookie.
Awesome
Does anyone know how to solve this error? `Please use only absolute URLs`
Yes. Code below working.
const url = req.nextUrl.clone();
return NextResponse.redirect(`${url.origin}/login`);
crypto error dude
Hey man this is quite misleading. The routes are not protected. Only the pages in /dashboard are protected, in other words, only the client-side pages are protected. You need to verify the jwt in the api folder.
Also, process.env will be NULL in _middleware in production mode. It won't verify.
Yes of course token should also be verified when a request is sent, but that is kind of common thing done by everyone and i don't think i need to explain that. This video's focus is using the _middleware file.
I already said it in the video i think, i'm not doing the full app, i'm just explaining concepts and ideas on how you can build things.
@@idavidgeo They can call next() when they see a token, and then verify it with getServerSideProps then. It's a pretty simple solution on how to verify it if they can't do it in _middleware.js file.
man you need to slow down speaking a little bit.
fix for absolute urls problem
const domain = req.nextUrl.clone()
domain.pathname = '/giris'
return NextResponse.redirect(domain)
FIXING Node.js module (crypto) which is not supported in the Edge Runtime ERROR:
Install jose (used instead of { verify } from jsonwebtoken, it doesnt work anymore)
In _middleware:
import * as jose from "jose";
Replace his try with:
try {
console.log("trying to verify jwt");
const verifying = await jose
.jwtVerify(jwt, new TextEncoder().encode(`${secret}`))
console.log("verifying", verifying);
return NextResponse.next();
}
Thanks bro. I encountered with this error now, how did you manage to fix it? I downgraded the version from 4.8.3 to 4.7.0, but still not working.
I'm getting this response:
{ [JWSInvalid: Compact JWS must be a string or Uint8Array] code: 'ERR_JWS_INVALID', name: 'JWSInvalid' }
@@hectorsum8102 Hey man, never got that error, make sure you use TextEncoder().encode(`${secret}`)) and make sure your secret is a valid string. Make a temp variable for the secret (e.g. let temp = "hello" and use that in place of secret in TextEncoder().encode(`${temp}`)) and see if it works, and narrow it down from there.
For anyone facing issues related to Edge-runtime try using *jose* or *jwt-decode* instead of *jsonwebtoken* for decoding the JWT.
do you mean verify?
@@CemretheFangirl *jwt-decode* is a small library and can only decode, can't validate JWT. Whereas if you have the secret, you will be able to validate the JWT using *jose* .
No point in using middleware in next 13. It's way too slow, waiting for them to improve it in future versions.
Tools to get cc easy in yt leakfullz