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.
Contact Us