This Gist contains a collection of Next.js Middleware examples that demonstrate various use cases and scenarios for enhancing your Next.js applications. Middleware in Next.js allows you to intercept, modify, and control the flow of requests and responses, making it a powerful tool for building robust web applications.
-
Authentication Middleware (
authenticationMiddleware.ts
):- Checks if the user is authenticated based on a session cookie.
- Redirects unauthenticated users to the login page.
- Ensures users have the necessary role to access protected routes.
-
Custom Response Middleware (
customResponseMiddleware.ts
):- Produces custom responses based on a condition.
- Demonstrates how Middleware can return custom error responses with status codes.
-
Request Logging Middleware (
loggingMiddleware.ts
):- Logs incoming requests, including method, URL, and timestamp.
- Useful for debugging and monitoring purposes.
-
Custom Header Middleware (
customHeadersMiddleware.ts
):- Sets a custom response header in the HTTP response.
- Shows how Middleware can customize response headers.
-
Request Body Parsing Middleware (
requestBodyParsingMiddleware.ts
):- Parses the request body, enabling working with data submitted via POST or PUT requests.
- Handles JSON, form data, and other request body formats.
-
CSRF Protection Middleware (
csrfProtectionMiddleware.ts
):- Helps protect against Cross-Site Request Forgery (CSRF) attacks.
- Generates and validates CSRF tokens in form submissions.
Each Middleware example is provided in a separate TypeScript file. You can include these files in your Next.js project and use them as Middleware functions in your application.
To use a Middleware function:
- Copy the content of the desired Middleware file (e.g.,
authenticationMiddleware.ts
). - Create a new file in your Next.js project with a
.ts
or.js
extension. - Paste the copied Middleware function into the new file.
- Import the Middleware function in your Next.js routes or other Middleware files.
- Apply the Middleware function to specific routes or route groups using Next.js configuration options or directly in your route handlers.
Make sure to customize the Middleware functions according to your application's requirements.
This collection of Next.js Middleware examples is provided under the MIT License. Feel free to use, modify, and distribute these examples in your projects.
How to use them?