Skip to main content

Sitecore

Sitecore JSS Development Essentials: Use of Middleware in Next.js

Man placing red block to bridge a gap between unpainted blocks

Middleware serve a purpose of augmenting or modifying the request and response objects before the request reaches the actual page or API route handler.

There can be instances where you want to validate if user has valid token or check if the request has valid header from security perspective or update cookies, log some information about request or response, add CORS header to response. Middleware file is best place to perform such actions.

Middleware handles requests before they reach the route handlers. It allows you to add additional functionality or perform tasks such as modify response by redirecting, rewriting, modifying the headers.

How to create Middleware
1) Middleware needs to be created in root folder. Right click on src folder, create file named as middleware.ts
2) Add middleware function which accepts Next Request
3) Perform logic and return response as required

Middleware

Now the question arises that is it possible to execute middleware based on some condition or for specific URLs only.

The answer is YES, you can add condition to check the request and its parameter and it also supports matcher config where you can specify paths, path with modifiers and regular expression:

Example:
export const config = { matcher: ‘/<desired path>/:path*’}

Middleware Catcher

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Mahima Patel

Mahima Patel is a Sitecore Architect, Working with Perficient for the last 9+ years. Sitecore 8, 9, 10 Professional Certified Developer.

More from this Author

Categories
Follow Us