Write custom middleware in Next.js using the middleware.ts file. Match specific paths and manipulate headers, cookies, and URLs.