{
    "componentChunkName": "component---src-pages-blog-markdown-remark-fields-slug-js",
    "path": "/blog/enhancing-your-nextjs-application-with-middleware",
    "result": {"data":{"markdownRemark":{"html":"<p>Next.js has quickly become a favorite framework for building modern web applications. One of its most powerful features is middleware—a mechanism that allows you to intercept and modify requests and responses before they reach your application. This post will explore what middleware is in Next.js, its key use cases, and how to implement it effectively. We’ll also look at how integrating <a href=\"https://supertokens.com/\" target=\"_blank\" rel=\"nofollow\">SuperTokens</a> can enhance your middleware functionality, to improve security and user experience. By the end of this guide, you’ll have a solid understanding of how middleware can help you build more robust, secure, and performant Next.js applications.</p>\n<h2 id=\"understanding-middleware-in-nextjs\" style=\"position:relative;\"><a href=\"#understanding-middleware-in-nextjs\" aria-label=\"understanding middleware in nextjs permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Understanding Middleware in Next.js</strong></h2>\n<p><span\n      class=\"gatsby-resp-image-wrapper\"\n      style=\"position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; \"\n    >\n      <a\n    class=\"gatsby-resp-image-link\"\n    href=\"/static/02b27569199e550f78cf99f179feceaa/37523/Understanding-Middleware-Flowchart-for-Next.js.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n    <span\n    class=\"gatsby-resp-image-background-image\"\n    style=\"padding-bottom: 95.56962025316456%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAATCAYAAACQjC21AAAACXBIWXMAAAsTAAALEwEAmpwYAAACi0lEQVQ4y42Ua1fiMBCGkzS3lt7bpYBtUaAgKiuXxa/6//8T8+5pueh6XPHDc+Y9k8lkkumUqeUN1EMJ9VB16IcSZlnC3o/QWwwRzQrkdxkGdYybkY+qcFHnBuNM4/bEONM0TjWqRB2YbIZQ8xHU4kSrmyHMbAB30odbJ+iNAoR9D0mq8SvRKGKFQSg/QkUo0Q/kgTllBqfK4dQnqhyyzKBuUuhhjGJ8g+quRjUuUVcjZLGPqKeRtHgKseu0UOQ6CK04MJH6EFlLcMJH54s9mDTA+vca+90eL/sXrFcbhEECz7roWRe+63fWSEZWchjJD4y7Gtwzn9BgVkF6Fn4YIIxShGEM11pwzo4wBkdwaOW2mgRnEJwdGJMCTDqfEGDOES+MkORDxFkfvSAC4xyMsQ7OBaS0raaT78DOi4yfYO+WC4HV8w6vr294fXvrNOPinJA4FySlS18n/BKOKM6Q5UOkWYEoyTrfewIOzjWuJaQPtsNaD8bYj75Oe16P8nxAUsqrFXYBRissFg12uy1ttxtqtbXmEqOUJs8LiXN+vcI2yPd9GgxGNJtNMZ1O0erA94mxcwIBIczPrqyNT0mWkxDmHNxupjTKSEnv/IYkpf22KaSNxt10gvvlI+pxDamcy9spJXE7rrFcPmI6uYM1loTz/wo7p1KKqrqmWdNQWZXkSOeyLqVEXVXUzBqqqpK0NnAcQ98mPFZpKEkLkurSvX8OzNKC1KmzV68cRCFm8waL+yUm0wl6fu+yIQx8WsznmM8XmDczJHFCV5uS5hnt9n9ou9vSZruhKIkuh6VJjNXTE63Xz7RaPVE/L7pOf9/lbvh5az9+X8dRbDvN2+lofwb8q2G4Nno/5pLwLxgGpMivo523AAAAAElFTkSuQmCC'); background-size: cover; display: block;\"\n  ></span>\n  <img\n        class=\"gatsby-resp-image-image\"\n        alt=\"Understanding Middleware Flowchart for Next.js\"\n        title=\"Understanding Middleware Flowchart for Next.js\"\n        src=\"/static/02b27569199e550f78cf99f179feceaa/f058b/Understanding-Middleware-Flowchart-for-Next.js.png\"\n        srcset=\"/static/02b27569199e550f78cf99f179feceaa/c26ae/Understanding-Middleware-Flowchart-for-Next.js.png 158w,\n/static/02b27569199e550f78cf99f179feceaa/6bdcf/Understanding-Middleware-Flowchart-for-Next.js.png 315w,\n/static/02b27569199e550f78cf99f179feceaa/f058b/Understanding-Middleware-Flowchart-for-Next.js.png 630w,\n/static/02b27569199e550f78cf99f179feceaa/37523/Understanding-Middleware-Flowchart-for-Next.js.png 720w\"\n        sizes=\"(max-width: 630px) 100vw, 630px\"\n        style=\"width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;\"\n        loading=\"lazy\"\n        decoding=\"async\"\n      />\n  </a>\n    </span></p>\n<p>Middleware functions in Next.js run on the server before a request is completed. By placing a <code class=\"language-text\">middleware.ts</code> or <code class=\"language-text\">middleware.js</code> file at the root of your project, you can define custom logic that executes during the request lifecycle. This logic allows you to intercept incoming requests, perform tasks such as authentication, logging, or even rewriting URLs, and then pass the modified request on to your application.</p>\n<p>In Next.js, middleware is executed on every request—or on specific routes, if configured—allowing you to implement cross-cutting concerns in a centralized way. This capability means you can protect sensitive routes, optimize performance, and enforce business rules without having to duplicate code across pages or API routes.</p>\n<p>For example, if you have a blog that needs to restrict access to premium content, middleware can check a user’s authentication status before the request reaches the protected pages. If the user isn’t authenticated, the middleware can redirect them to a login page.</p>\n<h2 id=\"key-use-cases-for-middleware\" style=\"position:relative;\"><a href=\"#key-use-cases-for-middleware\" aria-label=\"key use cases for middleware permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Key Use Cases for Middleware</strong></h2>\n<p><span\n      class=\"gatsby-resp-image-wrapper\"\n      style=\"position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; \"\n    >\n      <a\n    class=\"gatsby-resp-image-link\"\n    href=\"/static/00a10c994bb14974396c01a6addafde5/37523/Key-Use-Cases-for-Middleware.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n    <span\n    class=\"gatsby-resp-image-background-image\"\n    style=\"padding-bottom: 71.51898734177216%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAOCAYAAAAvxDzwAAAACXBIWXMAAAsTAAALEwEAmpwYAAACh0lEQVQ4y2VTy26bQBRFvGbABttgm5fBsTE2mOA4tdUkjtJHVpW6rLqvVKnqJh9Q9Qvab/U3cKp7E6pKXRy4j3POwJ0ZRVVVEDRNg67r0HUDtt1DEAQIw5ARxTGiKEKWZZjNZlyzLAu6YbCGtJ2P0hkZhgHTNKEqCnqWRJIkSJKY39F0gnAyxmKxwDzLuGZLwVzTNFjbGSudmTBNmEIiPbzHaJbD1DVIy+J3UL7CtDrC0FQIKWHoGkbJEtnxkXP6kM5UoYTQd1yk8zluv/xA/fYjwmCCoedjFoc4fvqG4+fvSJOYa2EwRf3wAaevP5HNL+A4LjofRQgBKQUGwxGaZofLaoOr5hKLfAXP81GsN9jVFZptiWJTYuR53NvvGuY2TYPByIMUAuSlSCl5wFTc7a5wur/Hzc0Ni8bTAHlRcE5YFWuMJwH37u7umLu/vmYteZCXQoFt21xcLHNGviqQphn8octiygnLvIA/cLlH+TN/heHIg23/NZTo9XpwHIcb/ngC3/cRpBfIXz8iCCOEER2bmGOupRfMIS5pSEsebEgP+sJ+v4+B62IwGPDQq5t3eHj6hXxT8RkkUPzm6Teq23fMIS5pSEsebEiDpN+mFVzX5dVmaYa6rlFvS5RlhShOGBTXVYl6u8UsnTOXNKQlD94U2upuY6jR69mIkxkOhwNOpxOa3Q6TaYBpEKKsKtzTRuz3vABxOzP5ch4VwzBa0zRbIURrWVYrpWyDMG6Lddku81W7KjatN54wVusN14pNyRzikoa05EFe/109HgHN1HH5wDovv8Qb5z7XqEcc4v57S/jqqap61jTtrOv62TAMhml2MM9CmGcpxFlKwTHVun7HJy15kNcfTRpbcr3syUcAAAAASUVORK5CYII='); background-size: cover; display: block;\"\n  ></span>\n  <img\n        class=\"gatsby-resp-image-image\"\n        alt=\"Key Use Cases for Middleware\"\n        title=\"Key Use Cases for Middleware\"\n        src=\"/static/00a10c994bb14974396c01a6addafde5/f058b/Key-Use-Cases-for-Middleware.png\"\n        srcset=\"/static/00a10c994bb14974396c01a6addafde5/c26ae/Key-Use-Cases-for-Middleware.png 158w,\n/static/00a10c994bb14974396c01a6addafde5/6bdcf/Key-Use-Cases-for-Middleware.png 315w,\n/static/00a10c994bb14974396c01a6addafde5/f058b/Key-Use-Cases-for-Middleware.png 630w,\n/static/00a10c994bb14974396c01a6addafde5/37523/Key-Use-Cases-for-Middleware.png 720w\"\n        sizes=\"(max-width: 630px) 100vw, 630px\"\n        style=\"width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;\"\n        loading=\"lazy\"\n        decoding=\"async\"\n      />\n  </a>\n    </span></p>\n<p>Middleware in Next.js is incredibly versatile. Below are some of the most common scenarios where middleware can be applied.</p>\n<h3 id=\"authentication-and-authorization\" style=\"position:relative;\"><a href=\"#authentication-and-authorization\" aria-label=\"authentication and authorization permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Authentication and Authorization</strong></h3>\n<p>One of the primary use cases for middleware is to validate user identity and permissions before granting access to specific routes. By checking cookies or session tokens, middleware can determine if a user is authenticated. If not, it can redirect them to a login page, and ensure that only authorized users access protected resources.</p>\n<h3 id=\"logging-and-analytics\" style=\"position:relative;\"><a href=\"#logging-and-analytics\" aria-label=\"logging and analytics permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Logging and Analytics</strong></h3>\n<p>Middleware is a great place to record request data for monitoring and analytics. You can log details such as the request URL, headers, or user-agent information. This data can be invaluable for debugging issues, tracking usage patterns, or even optimizing performance.</p>\n<h3 id=\"request-rewriting-and-redirection\" style=\"position:relative;\"><a href=\"#request-rewriting-and-redirection\" aria-label=\"request rewriting and redirection permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Request Rewriting and Redirection</strong></h3>\n<p>Sometimes, you need to modify request URLs or redirect users, based on certain conditions. Middleware can intercept a request and rewrite the URL before it reaches your page or API route. For example, if you’re migrating content, middleware can automatically redirect users from old URLs to new ones, without manual intervention.</p>\n<h3 id=\"security-enhancements\" style=\"position:relative;\"><a href=\"#security-enhancements\" aria-label=\"security enhancements permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Security Enhancements</strong></h3>\n<p>Security is paramount in any web application. Middleware can be used to implement measures such as bot detection, IP blocking, or rate limiting, to protect your resources from malicious actors. By placing these checks at the middleware level, you ensure that potentially harmful requests are filtered out early.</p>\n<h3 id=\"feature-flagging\" style=\"position:relative;\"><a href=\"#feature-flagging\" aria-label=\"feature flagging permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Feature Flagging</strong></h3>\n<p>With middleware, you can enable or disable features dynamically. This is particularly useful for testing new functionality or rolling out features gradually. For instance, you might only enable a new user interface for a subset of users, or you might disable a feature entirely if certain conditions aren’t met.</p>\n<h2 id=\"implementing-middleware-in-your-nextjs-project\" style=\"position:relative;\"><a href=\"#implementing-middleware-in-your-nextjs-project\" aria-label=\"implementing middleware in your nextjs project permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Implementing Middleware in Your Next.js Project</strong></h2>\n<p>Setting up middleware in your Next.js application is straightforward. Here’s a step-by-step guide to get you started:</p>\n<h3 id=\"1-create-the-middleware-file\" style=\"position:relative;\"><a href=\"#1-create-the-middleware-file\" aria-label=\"1 create the middleware file permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>1. Create the Middleware File</strong></h3>\n<p>In your Next.js project, create a file called <code class=\"language-text\">middleware.ts</code> (or <code class=\"language-text\">middleware.js</code> if you’re using JavaScript) at the root level, next to your <code class=\"language-text\">pages</code> or <code class=\"language-text\">app</code> directory. This file will contain all the logic for intercepting and handling requests.</p>\n<h3 id=\"2-define-the-middleware-function\" style=\"position:relative;\"><a href=\"#2-define-the-middleware-function\" aria-label=\"2 define the middleware function permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>2. Define the Middleware Function</strong></h3>\n<p>Inside your middleware file, export a function that receives a <code class=\"language-text\">NextRequest</code> object and returns a <code class=\"language-text\">NextResponse</code> object. This function will be executed for every request (or for the routes you specify).</p>\n<p>Here’s a simple example:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"6679861385284047000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`import { NextResponse, NextRequest } from 'next/server';\n\nexport function middleware(request: NextRequest) {\n    \n    // Log the URL of the incoming request\n    console.log('Request URL:', request.url);\n\n    // If the request is for a protected route, check for a valid token\n    if (request.nextUrl.pathname.startsWith('/protected')) {\n        \n        const token = request.cookies.get('token');\n\n        if (!token) {\n            return NextResponse.redirect(new URL('/login', request.url));\n        }\n    }\n\n    // Return the response unchanged\n    return NextResponse.next();\n}`, `6679861385284047000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"typescript\"><pre class=\"language-typescript\"><code class=\"language-typescript\"><span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> NextResponse<span class=\"token punctuation\">,</span> NextRequest <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/server'</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">function</span> <span class=\"token function\">middleware</span><span class=\"token punctuation\">(</span>request<span class=\"token operator\">:</span> NextRequest<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    \n    <span class=\"token comment\">// Log the URL of the incoming request</span>\n    <span class=\"token builtin\">console</span><span class=\"token punctuation\">.</span><span class=\"token function\">log</span><span class=\"token punctuation\">(</span><span class=\"token string\">'Request URL:'</span><span class=\"token punctuation\">,</span> request<span class=\"token punctuation\">.</span>url<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n    <span class=\"token comment\">// If the request is for a protected route, check for a valid token</span>\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">.</span>nextUrl<span class=\"token punctuation\">.</span>pathname<span class=\"token punctuation\">.</span><span class=\"token function\">startsWith</span><span class=\"token punctuation\">(</span><span class=\"token string\">'/protected'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n        \n        <span class=\"token keyword\">const</span> token <span class=\"token operator\">=</span> request<span class=\"token punctuation\">.</span>cookies<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'token'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n        <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>token<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n            <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">redirect</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token constant\">URL</span></span><span class=\"token punctuation\">(</span><span class=\"token string\">'/login'</span><span class=\"token punctuation\">,</span> request<span class=\"token punctuation\">.</span>url<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n        <span class=\"token punctuation\">}</span>\n    <span class=\"token punctuation\">}</span>\n\n    <span class=\"token comment\">// Return the response unchanged</span>\n    <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">next</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>In this example, the middleware logs each request’s URL. It then checks if the request is heading toward a protected route and verifies whether a valid token exists in the cookies. If the token is missing, it redirects the user to the login page. Otherwise, it allows the request to proceed.</p>\n<h3 id=\"3-configure-path-matching-optional\" style=\"position:relative;\"><a href=\"#3-configure-path-matching-optional\" aria-label=\"3 configure path matching optional permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>3. Configure Path Matching (Optional)</strong></h3>\n<p>Sometimes, you only want your middleware to run on specific routes. You can do this by exporting a <code class=\"language-text\">config</code> object from your middleware file. This object allows you to specify which paths the middleware should apply to.</p>\n<p>Example:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"85930274050893350000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`export const config = {\n    matcher: ['/protected/:path*', '/api/secure/:path*'],\n};`, `85930274050893350000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"typescript\"><pre class=\"language-typescript\"><code class=\"language-typescript\"><span class=\"token keyword\">export</span> <span class=\"token keyword\">const</span> config <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span>\n    matcher<span class=\"token operator\">:</span> <span class=\"token punctuation\">[</span><span class=\"token string\">'/protected/:path*'</span><span class=\"token punctuation\">,</span> <span class=\"token string\">'/api/secure/:path*'</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">,</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span></code></pre></div>\n<p>With this configuration, the middleware only runs for requests matching the specified patterns. This helps avoid unnecessary processing for routes where the middleware logic isn’t needed.</p>\n<h2 id=\"practical-examples-of-middleware-usage\" style=\"position:relative;\"><a href=\"#practical-examples-of-middleware-usage\" aria-label=\"practical examples of middleware usage permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Practical Examples of Middleware Usage</strong></h2>\n<p>To bring these concepts to life, let’s look at a few practical examples.</p>\n<h3 id=\"example-1-authentication-check\" style=\"position:relative;\"><a href=\"#example-1-authentication-check\" aria-label=\"example 1 authentication check permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Example 1: Authentication Check</strong></h3>\n<p>A common scenario is ensuring that only authenticated users can access certain pages. Suppose you have an app built with Next.js, and which has a premium section that requires users to log in. You can use middleware to intercept requests to the premium pages, check for a valid session or token, and then redirect unauthenticated users to the login page.</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"95071962173242030000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`export function middleware(request: NextRequest) {\n    \n    if (request.nextUrl.pathname.startsWith('/premium')) {\n        \n        const token = request.cookies.get('sessionToken');\n\n        if (!token) {\n            return NextResponse.redirect(new URL('/login', request.url));\n        }\n    }\n\n    return NextResponse.next();\n}`, `95071962173242030000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"typescript\"><pre class=\"language-typescript\"><code class=\"language-typescript\"><span class=\"token keyword\">export</span> <span class=\"token keyword\">function</span> <span class=\"token function\">middleware</span><span class=\"token punctuation\">(</span>request<span class=\"token operator\">:</span> NextRequest<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    \n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">.</span>nextUrl<span class=\"token punctuation\">.</span>pathname<span class=\"token punctuation\">.</span><span class=\"token function\">startsWith</span><span class=\"token punctuation\">(</span><span class=\"token string\">'/premium'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n        \n        <span class=\"token keyword\">const</span> token <span class=\"token operator\">=</span> request<span class=\"token punctuation\">.</span>cookies<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'sessionToken'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n        <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>token<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n            <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">redirect</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token constant\">URL</span></span><span class=\"token punctuation\">(</span><span class=\"token string\">'/login'</span><span class=\"token punctuation\">,</span> request<span class=\"token punctuation\">.</span>url<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n        <span class=\"token punctuation\">}</span>\n    <span class=\"token punctuation\">}</span>\n\n    <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">next</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>This simple check helps ensure that only users with a valid session can access premium content, thus protecting your resources and enhancing security.</p>\n<h3 id=\"example-2-geoip-based-content-delivery\" style=\"position:relative;\"><a href=\"#example-2-geoip-based-content-delivery\" aria-label=\"example 2 geoip based content delivery permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Example 2: GeoIP-Based Content Delivery</strong></h3>\n<p>Another practical use of middleware is delivering content based on the user’s geographic location. By using a third-party service or library to determine the user’s location from their IP address, you can modify the response to show region-specific content.</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"22274840698629485000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`import { NextResponse, NextRequest } from 'next/server';\nimport geoip from 'geoip-lite';\n\nexport function middleware(request: NextRequest) {\n    \n    const ip = request.ip ?? '8.8.8.8'; // Fallback IP for testing\n    const geo = geoip.lookup(ip);\n\n    if (geo && geo.country === 'IN') {\n        // Redirect users from India to a localized version of the site\n        const url = request.nextUrl.clone();\n        url.pathname = '/in' + url.pathname;\n        \n        return NextResponse.redirect(url);\n    }\n\n    return NextResponse.next();\n}`, `22274840698629485000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"typescript\"><pre class=\"language-typescript\"><code class=\"language-typescript\"><span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> NextResponse<span class=\"token punctuation\">,</span> NextRequest <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/server'</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">import</span> geoip <span class=\"token keyword\">from</span> <span class=\"token string\">'geoip-lite'</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">function</span> <span class=\"token function\">middleware</span><span class=\"token punctuation\">(</span>request<span class=\"token operator\">:</span> NextRequest<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    \n    <span class=\"token keyword\">const</span> ip <span class=\"token operator\">=</span> request<span class=\"token punctuation\">.</span>ip <span class=\"token operator\">??</span> <span class=\"token string\">'8.8.8.8'</span><span class=\"token punctuation\">;</span> <span class=\"token comment\">// Fallback IP for testing</span>\n    <span class=\"token keyword\">const</span> geo <span class=\"token operator\">=</span> geoip<span class=\"token punctuation\">.</span><span class=\"token function\">lookup</span><span class=\"token punctuation\">(</span>ip<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>geo <span class=\"token operator\">&amp;&amp;</span> geo<span class=\"token punctuation\">.</span>country <span class=\"token operator\">===</span> <span class=\"token string\">'IN'</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n        <span class=\"token comment\">// Redirect users from India to a localized version of the site</span>\n        <span class=\"token keyword\">const</span> url <span class=\"token operator\">=</span> request<span class=\"token punctuation\">.</span>nextUrl<span class=\"token punctuation\">.</span><span class=\"token function\">clone</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n        url<span class=\"token punctuation\">.</span>pathname <span class=\"token operator\">=</span> <span class=\"token string\">'/in'</span> <span class=\"token operator\">+</span> url<span class=\"token punctuation\">.</span>pathname<span class=\"token punctuation\">;</span>\n        \n        <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">redirect</span><span class=\"token punctuation\">(</span>url<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token punctuation\">}</span>\n\n    <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">next</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>This middleware example checks the user’s IP, looks up the geographic location, and then redirects users from India to a localized version of your site. Such functionality can improve user experience by serving more relevant content.</p>\n<h2 id=\"how-supertokens-enhances-middleware-functionality\" style=\"position:relative;\"><a href=\"#how-supertokens-enhances-middleware-functionality\" aria-label=\"how supertokens enhances middleware functionality permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>How SuperTokens Enhances Middleware Functionality</strong></h2>\n<p><span\n      class=\"gatsby-resp-image-wrapper\"\n      style=\"position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; \"\n    >\n      <a\n    class=\"gatsby-resp-image-link\"\n    href=\"/static/04ed09bafa0c4b8349eb1a3a678d9afb/7ebf9/Supertokens.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n    <span\n    class=\"gatsby-resp-image-background-image\"\n    style=\"padding-bottom: 50.632911392405056%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAKCAYAAAC0VX7mAAAACXBIWXMAAA7DAAAOwwHHb6hkAAACP0lEQVQozx3R227bRhRGYRa1LJ6HM5whh8OjKcqhLUeQ7ToJgrYIolh2DCQBmt7mkfzMK5Au9t3Guvg/r7aG69Gx3VxxPc/0bUvX9XT9SDOsqboJ3axQticvG0rbYEuHLSuMMQgh2G63vL6+stvt8KSUGK05hletYx575mlk6EemNzf0l28Zh4mLacPlekNftdRK41SOTgVJlLD0Q/7484zF+RJPZoKqyOnrkqlzrPuasXWMw8BfDx+42T2wubrhbvfA/faW+/mKtTH0Sp2iKtNEqSYUGj9K8USaUGpFXWqaUnPRWKah42p+w38//+fw9MI//+55fnzm++GZb58+8W41clmW1HmBUpZI1fiyZhkrvDSOyKXAqIxSS1pnedx/5uXrC7d393zeP/J0eOZp/4UfhwM/v+z59f0bTx//plIWpTtCPbDUFywSgyfiCJnGSJGQywytJLmSOOeo65q6drSuYt04rpuKt03FXBb0ucHqBmEGlvlI4mYS0+AVIkKnESIOSZMYkaYnOaMkRS6pTE5daNrjzkVOm2e0KsNKjVIVcd5xlrW49T3d6gbvQic0KkbGAXEYEh4visj8BYUUDLWjd5ZVW9O7isw/R4dLZJqdMHxhOUstRbPGVj3epkqZTIJJA9LQx/d9wiBAxAGlCOhNzHa0XHc5vQ6xIkDGPlEYnVSPEIsgIRt2yGGHd1sL5jLBihARHYNLAt8niwMqFTJVCbuVYTsoVjamkiFZ7J9+ln6AH8acny8Qwx1ifM9vqdoHJdKZY1wAAAAASUVORK5CYII='); background-size: cover; display: block;\"\n  ></span>\n  <img\n        class=\"gatsby-resp-image-image\"\n        alt=\"Supertokens\"\n        title=\"Supertokens\"\n        src=\"/static/04ed09bafa0c4b8349eb1a3a678d9afb/f058b/Supertokens.png\"\n        srcset=\"/static/04ed09bafa0c4b8349eb1a3a678d9afb/c26ae/Supertokens.png 158w,\n/static/04ed09bafa0c4b8349eb1a3a678d9afb/6bdcf/Supertokens.png 315w,\n/static/04ed09bafa0c4b8349eb1a3a678d9afb/f058b/Supertokens.png 630w,\n/static/04ed09bafa0c4b8349eb1a3a678d9afb/40601/Supertokens.png 945w,\n/static/04ed09bafa0c4b8349eb1a3a678d9afb/78612/Supertokens.png 1260w,\n/static/04ed09bafa0c4b8349eb1a3a678d9afb/7ebf9/Supertokens.png 1919w\"\n        sizes=\"(max-width: 630px) 100vw, 630px\"\n        style=\"width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;\"\n        loading=\"lazy\"\n        decoding=\"async\"\n      />\n  </a>\n    </span></p>\n<p>Integrating third-party tools with middleware can significantly extend its capabilities. One excellent example is <a href=\"https://supertokens.com/\" target=\"_blank\" rel=\"nofollow\">SuperTokens</a>, an open-source authentication solution that integrates seamlessly with Next.js middleware. SuperTokens provides a robust foundation for managing user sessions and enhancing security in your application.</p>\n<h3 id=\"session-management\" style=\"position:relative;\"><a href=\"#session-management\" aria-label=\"session management permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Session Management</strong></h3>\n<p>SuperTokens simplifies session management by handling token creation, rotation, and validation. By integrating SuperTokens with your middleware, you can easily verify session validity without having to write complex authentication logic from scratch.</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"72678213585885150000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`import { NextResponse, NextRequest } from 'next/server';\nimport geoip from 'geoip-lite';\n\nexport function middleware(request: NextRequest) {\n    \n    const ip = request.ip ?? '8.8.8.8'; // Fallback IP for testing\n    const geo = geoip.lookup(ip);\n\n    if (geo && geo.country === 'IN') {\n        // Redirect users from India to a localized version of the site\n        const url = request.nextUrl.clone();\n        url.pathname = '/in' + url.pathname;\n        \n        return NextResponse.redirect(url);\n    }\n\n    return NextResponse.next();\n}`, `72678213585885150000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"typescript\"><pre class=\"language-typescript\"><code class=\"language-typescript\"><span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> NextResponse<span class=\"token punctuation\">,</span> NextRequest <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/server'</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">import</span> geoip <span class=\"token keyword\">from</span> <span class=\"token string\">'geoip-lite'</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">function</span> <span class=\"token function\">middleware</span><span class=\"token punctuation\">(</span>request<span class=\"token operator\">:</span> NextRequest<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    \n    <span class=\"token keyword\">const</span> ip <span class=\"token operator\">=</span> request<span class=\"token punctuation\">.</span>ip <span class=\"token operator\">??</span> <span class=\"token string\">'8.8.8.8'</span><span class=\"token punctuation\">;</span> <span class=\"token comment\">// Fallback IP for testing</span>\n    <span class=\"token keyword\">const</span> geo <span class=\"token operator\">=</span> geoip<span class=\"token punctuation\">.</span><span class=\"token function\">lookup</span><span class=\"token punctuation\">(</span>ip<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>geo <span class=\"token operator\">&amp;&amp;</span> geo<span class=\"token punctuation\">.</span>country <span class=\"token operator\">===</span> <span class=\"token string\">'IN'</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n        <span class=\"token comment\">// Redirect users from India to a localized version of the site</span>\n        <span class=\"token keyword\">const</span> url <span class=\"token operator\">=</span> request<span class=\"token punctuation\">.</span>nextUrl<span class=\"token punctuation\">.</span><span class=\"token function\">clone</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n        url<span class=\"token punctuation\">.</span>pathname <span class=\"token operator\">=</span> <span class=\"token string\">'/in'</span> <span class=\"token operator\">+</span> url<span class=\"token punctuation\">.</span>pathname<span class=\"token punctuation\">;</span>\n        \n        <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">redirect</span><span class=\"token punctuation\">(</span>url<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token punctuation\">}</span>\n\n    <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">next</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>In this snippet, the middleware uses SuperTokens’ <code class=\"language-text\">verifySession</code> function to check if the user’s session is valid. If the session is invalid, the user is redirected to the login page.</p>\n<h3 id=\"token-theft-detection\" style=\"position:relative;\"><a href=\"#token-theft-detection\" aria-label=\"token theft detection permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Token Theft Detection</strong></h3>\n<p>SuperTokens also implements security measures such as rotating refresh tokens and using short-lived access tokens. These features allow middleware to detect potential token theft scenarios. If a token is compromised, the system can invalidate it and force a new authentication process, significantly enhancing security.</p>\n<h3 id=\"scalability\" style=\"position:relative;\"><a href=\"#scalability\" aria-label=\"scalability permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Scalability</strong></h3>\n<p>For high-traffic applications, scalability is crucial. SuperTokens is designed to handle large volumes of requests efficiently. When incorporated into your Next.js middleware, it ensures that the authentication checks remain fast and do not become a performance bottleneck.</p>\n<p>By leveraging SuperTokens in your middleware, you can build robust authentication mechanisms quickly, to reduce the risk of security breaches and ensure that only authorized users access your protected routes.</p>\n<h2 id=\"best-practices-for-using-middleware\" style=\"position:relative;\"><a href=\"#best-practices-for-using-middleware\" aria-label=\"best practices for using middleware permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Best Practices for Using Middleware</strong></h2>\n<p>To get the most out of Next.js middleware, here are some best practices to consider:</p>\n<h3 id=\"performance-considerations\" style=\"position:relative;\"><a href=\"#performance-considerations\" aria-label=\"performance considerations permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Performance Considerations</strong></h3>\n<ul>\n<li>\n<p><strong>Optimize Middleware Logic:</strong> Since middleware runs on every request (or for matched routes), it’s critical to ensure that the logic is optimized for performance. Avoid heavy computations or blocking operations that could slow down the request lifecycle.</p>\n</li>\n<li>\n<p><strong>Keep it Lightweight:</strong> Aim to perform only essential checks in middleware and defer more complex operations to your API routes or client-side code.</p>\n</li>\n</ul>\n<h3 id=\"security-measures\" style=\"position:relative;\"><a href=\"#security-measures\" aria-label=\"security measures permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Security Measures</strong></h3>\n<ul>\n<li>\n<p><strong>Sanitize Inputs:</strong> Always validate and sanitize inputs within your middleware, to prevent security vulnerabilities like injection attacks.</p>\n</li>\n<li>\n<p><strong>Handle Exceptions Gracefully:</strong> Ensure your middleware catches errors and responds appropriately, rather than letting exceptions propagate and potentially crash your server.</p>\n</li>\n</ul>\n<h3 id=\"modularization\" style=\"position:relative;\"><a href=\"#modularization\" aria-label=\"modularization permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Modularization</strong></h3>\n<p>While Next.js supports a single middleware file, you can maintain cleaner code by organizing your logic into separate modules. Import functions from other files to keep your middleware file concise and maintainable. This modular approach makes it easier to manage and update your middleware logic as your application grows.</p>\n<h3 id=\"configuration-and-testing\" style=\"position:relative;\"><a href=\"#configuration-and-testing\" aria-label=\"configuration and testing permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Configuration and Testing</strong></h3>\n<ul>\n<li>\n<p><strong>Use Config Object:</strong> Leverage the <code class=\"language-text\">config</code> object to specify to which paths your middleware should apply. This targeted approach helps reduce unnecessary processing.</p>\n</li>\n<li>\n<p><strong>Test Thoroughly:</strong> Ensure you test your middleware in various scenarios, including edge cases. Testing helps catch issues early and ensures that your middleware behaves as expected under different conditions.</p>\n</li>\n</ul>\n<h2 id=\"conclusion\" style=\"position:relative;\"><a href=\"#conclusion\" aria-label=\"conclusion permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a><strong>Conclusion</strong></h2>\n<p>Middleware in Next.js is a powerful tool for intercepting and modifying requests, to enhance performance, security, and user experience. It allows you to implement functionalities like authentication, logging, and request rewriting, without scattering logic throughout your application. Using solutions like <a href=\"https://supertokens.com/\" target=\"_blank\" rel=\"nofollow\">SuperTokens</a> can strengthen your middleware, by adding robust session management and token theft detection.</p>\n<p>To succeed with middleware, keep it lightweight and focused, optimize functions for essential tasks, and delegate complex operations elsewhere. This ensures high performance and a smooth user experience. By leveraging Next.js middleware and integrating tools like SuperTokens, you can create responsive, secure, and dynamic web applications. Understanding and using middleware effectively will be an invaluable part of your development toolkit.</p>","frontmatter":{"date":"April 12, 2025","title":"Enhancing Your Next.js Application with Middleware","cover":"enhancing-your-nextjs-application-with-middleware.png","author":"Mostafa Ibrahim","description":"Transform your Next.js app with middleware! Learn essential strategies to enhance functionality and streamline your development process today."},"fields":{"slug":"/enhancing-your-nextjs-application-with-middleware/"}},"site":{"siteMetadata":{"title":"SuperTokens Blog"}}},"pageContext":{"id":"732ab660-4bcf-5a9e-afd8-190b11046e64","fields__slug":"/enhancing-your-nextjs-application-with-middleware/","__params":{"fields__slug":"enhancing-your-nextjs-application-with-middleware"}}},
    "staticQueryHashes": []}