Integrate custom middleware
Integrating a custom middleware implementation in Content SDK involves extending the Middleware abstract class and passing the middleware instance as a parameter to defineMiddleware.
To integrate custom middleware:
-
Create a custom middleware class by extending
Middleware(orMiddlewareBaseif you want to inherit the default Sitecore methods). -
Implement the
handlemethod to process requests. -
Instantiate the middleware.
-
Pass the middleware instance to
defineMiddlewarein the Next.js middleware function definition.
Example integration
The following example demonstrates how to seamlessly integrate a simple custom middleware that logs a request URL:
import { defineMiddleware, Middleware } from '@sitecore-content-sdk/nextjs/middleware';
import { NextRequest, NextFetchEvent } from 'next/server';
...
class LoggerMiddleware extends Middleware {
async handle(req: NextRequest, res: NextResponse): Promise<NextResponse> {
console.log(`Request to ${req.url}`);
return res;
}
}
const logger = new LoggerMiddleware();
export function middleware(req: NextRequest, ev: NextFetchEvent) {
return defineMiddleware(logger, multisite, redirects, personalize).exec(req, ev);
}There's no official method or helper to identify whether you're in the Editing mode inside your middleware. As a workaround, you can use the following Sitecore cookies to check whether you're in the Editing mode in your middleware:
-
sc_headless_mode -
sitename#sc_mode
Next.js also provides the __next_preview_data and __prerender_bypass cookies to enable Preview Mode (Pages Router) or Draft Mode (App Router).