Using the crypto Web API to redirect requests with a unique token

Learn how to use the Crypto Web API in your Edge Middleware.
Last updated on August 2, 2024
Middleware

The following example shows how to use the crypto Web API in your Edge Middleware to redirect requests with a unique token.

Your middleware file should be placed at the root of your project. If you are using the src directory, the file should be placed in the src directory.

middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
 
export const config = {
  matcher: '/',
};
 
export function middleware(request: NextRequest) {
  const token = crypto.randomUUID();
  const url = request.nextUrl;
 
  url.pathname = '/api/crypto';
  url.searchParams.set('token', token);
 
  return NextResponse.redirect(url);
}