---
title: "Integrate custom middleware"
slug: "integrate-custom-middleware"
abstract: ""
---
# 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:

1. Create a custom middleware class by extending `Middleware` (or `MiddlewareBase` if you want to inherit the default Sitecore methods).
2. Implement the `handle` method to process requests.
3. Instantiate the middleware.
4. Pass the middleware instance to `defineMiddleware` in 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:

```ts
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);
}
```

> [!note]
> 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](http://nextjs.org/docs/pages/guides/preview-mode) (Pages Router) or [Draft Mode](https://nextjs.org/docs/app/guides/draft-mode) (App Router).