Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Authentication with middlewares in NextJS

Posted on Aug 13 Hey there! Today, we're going to talk about Authentication in Next.js using middlewares. If you're not familiar, Next.js is a really cool framework for building server-rendered React applications.So, what's authentication all about? Well, it's a way to make sure that only the right people can access certain parts of your web app. And that's where middlewares come in handy! They're like helpers that can do certain things before requests reach the actual route handlers.This article will discuss the fundamentals of middlewares and demonstrate how they can be utilized in a Next.js application to establish a secure authentication system. Upon reading this article, you'll acquire a comprehensive understanding of how to utilize middlewares for authentication in Next.js and have the ability to enhance the security of your web apps. Let's begin and explore the world of authentication with Next.js.First, we have to have a NextJS project, then install Axios for better HTTP HandlingNext we have to define a service, in this case AuthService to handle authentication:This code defines a class named AuthService that exports it as a module. The AuthService class has a constructor that takes a URL as a parameter to create an Axios instance based on that URL. Axios is a popular JavaScript library used to make HTTP requests from a web browser or Node.js.The login method is defined within the AuthService class, which takes two parameters, username and password. This method sends a POST request to the /login endpoint of the API service using the Axios instance created in the constructor. The username and password are passed as an object in the POST request body.If the POST request is successful, the method returns an object that contains the username, avatar, id, accessToken, and expiredAt properties. These properties are extracted from the response data, which is received from the API service. Overall, this code defines a reusable AuthService class that encapsulates the logic for making an HTTP request to an API service to log in a user and retrieves the user's information.We need 3 types of routes:We need a hook to handle login function:This code exports a function named useLogin that returns an object with the login function. The login function takes two parameters: username and password. Within the login function, an asynchronous call is made to authService.login(username, password), which is a method defined in another module, authService. This method returns a promise that resolves to a User object.If the User object is truthy, meaning it exists, the Cookies.set method is called to set a cookie named "currentUser" with the stringified User object as its value.Finally, the login function returns the User object as a type assertion to inform TypeScript that the returned value is indeed a User.This is the most important part of the article, using built-in middleware.ts of NextJS:This code defines a middleware function that is used in a Next.js application. Middlewares are functions that can modify incoming requests and outgoing responses in a web application.The middleware function takes a NextRequest object as its parameter, which is provided by the Next.js server. The NextRequest object represents an incoming request and contains information about the URL, headers, cookies, and other request-specific data.The middleware function first retrieves the currentUser cookie from the request using request.cookies.get("currentUser")?.value. If the requested URL is a protected route (defined in protectedRoutes), and the currentUser cookie is not present or has expired, the middleware will delete the currentUser cookie and redirect the user to the login page using NextResponse.redirect(new URL("/login", request.url)). The response.cookies.delete("currentUser") statement removes the currentUser cookie from the response object. If the requested URL is an authentication route (defined in authRoutes) and the currentUser cookie is present, the middleware will redirect the user to the profile page using NextResponse.redirect(new URL("/profile", request.url)).In conclusion, this article has covered the fundamentals of authentication using middlewares in Next.js. We've discussed how middlewares can be used to manage authentication in web applications by intercepting incoming requests and performing necessary actions before they reach the actual route handlers. We've also explored how to implement a secure authentication system using middlewares in a Next.js application. If you find this article is too confusing, you can check out the source code: https://github.com/superdev163/nextjs-authTemplates let you quickly answer FAQs or store snippets for re-use. Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well Confirm For further actions, you may consider blocking this person and/or reporting abuse David - Aug 4 Cathal Mac Donnacha 🚀 - Aug 4 Kiran Mantha - Aug 4 Kamonwan Achjanis - Aug 4 Once suspended, brainiacneit will not be able to comment or publish posts until their suspension is removed. Once unsuspended, brainiacneit will be able to comment and publish posts again. Once unpublished, all posts by brainiacneit will become hidden and only accessible to themselves. If brainiacneit is not suspended, they can still re-publish their posts from their dashboard. Note: Once unpublished, this post will become invisible to the public and only accessible to Super. They can still re-publish the post if they are not suspended. Thanks for keeping DEV Community safe. Here is what you can do to flag brainiacneit: brainiacneit consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy. Unflagging brainiacneit will restore default visibility to their posts. DEV Community — A constructive and inclusive social network for software developers. With you every step of your journey. Built on Forem — the open source software that powers DEV and other inclusive communities.Made with love and Ruby on Rails. DEV Community © 2016 - 2023. We're a place where coders share, stay up-to-date and grow their careers.



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

Authentication with middlewares in NextJS

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×