Reading list Switch to dark mode

    How to Implement Authentication using NextJS Middleware.

    Updated 10 April 2023

    Introduction

    In this blog we’re going to implementing authentication using NextJS middleware.
    for implementing this functionality we need these resources .
    1. js-cookie lib ( for add and remove cookie from the NextJS app).
    2. NextJS Middleware. ( Concept of the NextJS)

    UI and Layout.

    For form design you can create your own custom design which is better, but if you need some recommendation so you can check this blog 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.

    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 in nextjs , 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. and able to do redirecting , rewriting on the incoming request. and middleware run before the cache content, so user can modify the static files and pages.

    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.

    Step – 1 (Add the route in which you want to authentication).

    First 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.

    Start your headless eCommerce
    now.
    Find out More
    // Supports both a single string value or an array of matchers
    export const config = {
      matcher: ['/route-which-you-want-to-authenticated'],
    }

    Step – 2 (Add redirect functionality when user is authenticate or not).

    Now we’re going to set the redirect functionality for redirect to login page or any desired page if user is not authenticated. 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. if cookies is empty we redirect to login-page screen or any desired page you want to route. if it’s available we route to homepage or any desired page you want to route.

    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('/desired-route',request.url))
      }
    
      else {
       return NextResponse.redirect(new URL('/desired-route', request.url))
      }
    }
    
    export const config = {
      matcher: '/desired-route',
    }

    Conclusion

    Now because of middleware authentication your nextjs-app will authenticate on server side. and you don’t need to add authentication on every pages, it’ll handle globally.
    If you like this blog, you can check my blog on the Implement magento graphQl api with NextJS .
    Happy Coding !!

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home