Today I'll be Working on implementing a simple auth system to my protected /admin routes on this blog using JSON Web Tokens! To start, some context on the state of my application. I already have set up the admin/login route and the admin/dashboard route. and right now the dashboard is completely unprotected which means I can access by typing the route on the browser and that's exactly what I want to change.
Upon reading NextJS Docs, we need to create the middleware in the root directory.
For now I just copied and Paste some CORS configuration, and I'm making sure I can get a token if any, and read the correct method and the path being called, Also in the config variable we are using the matcher to run the middleware when we request these paths.
This is what we see after loading the /admin/login page. Now Let's set up protected routes:
instead of just returning next():
testing /admin , redirected to /login ( no token ) testing /admin/dashboard , redirected to /login (no token)
Next, we will create a POST request to handle the form data. We will call our database (Prisma in this case) and bcrypt to compare the password since I've used bycript to generate a strong password encryption field on the db when the admin was created.
Upon valid pwMatch, we'll create a token with the user object as payload. ( notice we added a role for fun 😄) moving on... we need the helpers!
I'll create a new file 'token.js' as a utility helper in my /utils folder. also we will use a library called 'jose'
As you can see I'm using Formik for this form, and onSubmit we will post to the API route, validate the user, return a token and set the token as a cookie that expires in 7 days yes, we are using toasts for custom alerts! Should we login? We have protected our /admin routes , Cookies are set! Great Work 👏 (Console Warning is letting me know about how to properly set cookie parameters , but that's something for other day....)
I hope you were able to follow along and managed to implement your own solution , this was mine ! I don't know if it's secure enough or if there is quicker and more efficient way to do this, let me know in the Comments!