withCroct
Wrap a Next.js API route handler with the Croct middleware.
This higher-order function wraps a Next.js API route handler with the Croct middleware.
If your project already has a Next.js API route handler, you can use this function to configure the Croct middleware while preserving the current handler logic.
It also provides a way to identify and anonymize users for request-based authentication via headers or cookie.
Signature
You can use this function without arguments, which is equivalent to using the middleware function:
function withCroct(): NextApiHandler
Alternatively, you can pass a handler function as the first argument and optionally a user ID resolver function as the second argument:
export function withCroct(next: NextMiddleware, userIdResolver?: UserIdResolver): NextMiddleware;
And lastly, you can pass an options object as a single argument:
export function withCroct(props: CroctMiddlewareOptions): NextMiddleware;
Example
Here is an example of how to use this function:
import {NextResponse} from 'next/server';import {withCroct} from '@croct/plug-next/middleware';function log(request) {console.log(request.headers.get('user-agent'));return NextResponse.next({headers: request.headers});}export const middleware = withCroct(log);`
Parameters
The following list describes the supported parameters:
- options(optional)object
The middleware options.
- next(optional)NextMiddleware
The handler function to execute after the Croct middleware.
The function receives the request object and returns a response object.
- userIdResolver(optional)(request: NextRequest)=>Promise<string|null>
A function that resolves the user ID for the current request.
The function receives the request object and returns the user ID as a string or null if the user is anonymous.
- next(optional)