Introduction
Here, we’re going to implement authentication using middleware. To setup a nextjs project you can checkout this blog to setup a next js project efficiently “How to setup a project in NextJs“
To implement this functionality we need these resources.
1. js-cookie: This library is used to add and remove cookie from the app.
2. NextJS Middleware. ( Concept of the Next.Js)
UI and Layout In NextJs
For form design, you can create your own custom design, which is often better.
However, if you need some recommendations, you can check this blog for helpful insights and suggestion How to Implement useForm() Hook in Nextjs | React.
In this blog UI part and validation of the form both are very well managed.
Cookie and its Implementation In NextJs
Add Cookie.
import Cookies from 'js-cookie' Cookies.set('your-key-name', 'your-key-value')
Remove Cookie.
Cookies.remove('your-key-name')
Get Cookie
Cookies.get('your-key-name')
these are the methods which we’re going to use to achieve the Authentication functionality, If you want to know more about the JS-Cookie library you can visit the js-cookie library documentation.
NextJS Middleware
NextJS middleware allows user to run code on server end before request is completed.
Then based on the incoming request, user can modify the request and response header.
Additionally, we can handle redirecting and rewriting on incoming requests, as middleware runs before cached content. This allows us to modify static files and pages effectively.
These are the following steps we need to do setup middleware authentication in NextJS.
1. Add the route in which you want to authentication.
2. Add redirect functionality when user is authenticate or not.
Add the route in which you want to authentication
Firstly, you need to add middleware file in your NextJS app at the same level as your pages
(in the root or src
directory).
After that add those route which you want to authenticate in middleware.js file.
// Supports both a single string value or an array of matchers export const config = { matcher: ['/route-which-you-want-to-authenticated'], }
Add redirect functionality when user is authenticate or not
Now, further we’re going to set the redirect functionality to redirect to login page or any desired page if user is not authenticated.
And For that, we going to use NextRequest of next/server. it provide us the request object, and by this object we get the cookies data.
When the cookies are empty, we redirect the user to the login page or any desired page of your choice.
However Conversely, if the cookies are available, we route the user to the homepage or another specified page.
import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' export function middleware(request: NextRequest) { const userToken = request.cookies.get('your-key')?.value; if(!userToken) { return NextResponse.redirect(new URL('/login',request.url)) } else { return NextResponse.redirect(new URL('/', request.url)) } } export const config = { matcher: '/desired-route', }
Conclusion
Now, with middleware authentication, your Next.js app will authenticate on the server side.
As a result, you won’t need to add authentication to every page; it will be handled globally.
If you like this blog, you can check my blog on the Implement magento graphQl api with NextJS.
Happy Coding !!
1 comments