Functioning of a Middleware

  • HOC Initialization – When using a middleware function with a component, the middleware function runs first.
  • Middleware Logic – Middleware contains special logic related to middleware purposes. This logic may be authentication, authorization, or data fetching.
  • Component Rendering – After the middleware logic runs, it decides whether to render a wrapped component or not.
  • Conditional Rendering – If the middleware allows, the wrapped component is rendered with necessary props.
  • Redirect or Alternative rendering – If the middleware logic denies rendering the wrapped component, the middleware performs a redirect to another page, an alternative component.

Example: In this example, We will secure the profile page within an authentication middleware with the help of a higher-order component (HOC) to envelop the profile page component. This higher-order component will interfere with the request to the profile page, ensuring that only users with valid credentials can access it.

Next JS Middleware: Extending Functionality in Your Application

Middleware plays an important role in creating backend applications which are used to intercept incoming requests, perform actions, and modify responses before send to routing handlers. In this article, we will understand middleware in Next.js by creating an authentication middleware.

Similar Reads

Prerequisites:

JavaScript/TypeScript ReactJS basics NextJS...

What are Middlewares?

Middleware is a piece of code that redefines the functionality of your written logic. It enhances the logic and provides an additional capability. It has access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. Middleware modifies a request before it reaches the destination. It is very helpful in performing tasks like authentication and data manipulation....

Functioning of a Middleware

HOC Initialization – When using a middleware function with a component, the middleware function runs first. Middleware Logic – Middleware contains special logic related to middleware purposes. This logic may be authentication, authorization, or data fetching. Component Rendering – After the middleware logic runs, it decides whether to render a wrapped component or not. Conditional Rendering – If the middleware allows, the wrapped component is rendered with necessary props. Redirect or Alternative rendering – If the middleware logic denies rendering the wrapped component, the middleware performs a redirect to another page, an alternative component....

Steps to Create a Next.js app

Step 1: Create a Next.js app by using the command provided below....

Contact Us