{
    "componentChunkName": "component---src-pages-blog-markdown-remark-fields-slug-js",
    "path": "/blog/mastering-nextjs-api-routes",
    "result": {"data":{"markdownRemark":{"html":"<p>Next.js API Routes offer a powerful way to add backend functionality to your Next.js projects, without the need for a separate server or extensive configuration. By creating serverless functions within your application, you can handle requests, interact with databases, and\nintegrate with authentication services—all in one unified framework. In this guide, we’ll explore what API Routes are, how they differ from traditional backend APIs, and then share best practices for building, testing, and securing these routes. We’ll also look at integrating SuperTokens for secure session management. Whether you’re a seasoned developer or just getting started, this guide will help you harness the power of Next.js API Routes and create robust backend solutions.</p>\n<h2 id=\"what-are-api-routes-in-nextjs\" style=\"position:relative;\"><a href=\"#what-are-api-routes-in-nextjs\" aria-label=\"what are api routes 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>What Are API Routes in Next.js?</strong></h2>\n<p>Next.js API Routes let you create serverless endpoints directly within your application. By placing files in the <code class=\"language-text\">/pages/api</code> directory, each file becomes an endpoint that can handle HTTP requests. This built-in serverless support simplifies deployment, as your frontend and backend code share the same codebase and infrastructure.</p>\n<h3 id=\"comparison-with-traditional-backend-apis\" style=\"position:relative;\"><a href=\"#comparison-with-traditional-backend-apis\" aria-label=\"comparison with traditional backend apis 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>Comparison with Traditional Backend APIs</strong></h3>\n<p>While frameworks like Node.js/Express or Django require a separate backend server, Next.js API Routes provide a lightweight alternative that integrates into your Next.js project. The benefits include:</p>\n<ul>\n<li>\n<p><strong>Built-in Serverless Support:</strong> Automatically scales with your application.</p>\n</li>\n<li>\n<p><strong>Seamless Integration with Frontend:</strong> Share code, models, and utilities between client and server.</p>\n</li>\n<li>\n<p><strong>Simplified Deployment:</strong> Fewer moving parts mean faster development cycles.</p>\n</li>\n</ul>\n<h2 id=\"setting-up-your-first-api-route-in-nextjs\" style=\"position:relative;\"><a href=\"#setting-up-your-first-api-route-in-nextjs\" aria-label=\"setting up your first api route 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>Setting Up Your First API Route in Next.js</strong></h2>\n<h3 id=\"creating-a-simple-api-route\" style=\"position:relative;\"><a href=\"#creating-a-simple-api-route\" aria-label=\"creating a simple api route 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>Creating a Simple API Route</strong></h3>\n<ol>\n<li>\n<p><strong>Create the Directory</strong></p>\n<p>Next.js automatically treats files in the <code class=\"language-text\">/pages/api</code> directory as API endpoints. If the directory doesn’t exist, create it at the root of your project.</p>\n</li>\n<li>\n<p><strong>Create a File</strong></p>\n<p>In the <code class=\"language-text\">/pages/api</code> directory, create the file (e.g., <code class=\"language-text\">hello.js</code>) that will export a handler function.</p>\n</li>\n<li>\n<p><strong>Define the Handler</strong></p>\n<p>Here’s an example of a simple API route that returns a greeting:</p>\n</li>\n</ol>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"18538504818622337000\"\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(`// pages/api/hello.js\n\nexport default function handler(req, res) {\n  res.status(200).json({ message: &quot;Hello from Next.js API Routes!&quot; });\n}`, `18538504818622337000`)\"\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=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token comment\">// pages/api/hello.js</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> <span class=\"token keyword\">function</span> <span class=\"token function\">handler</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">req<span class=\"token punctuation\">,</span> res</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">200</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> <span class=\"token literal-property property\">message</span><span class=\"token operator\">:</span> <span class=\"token string\">\"Hello from Next.js API Routes!\"</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<ol start=\"4\">\n<li>\n<p><strong>Access the Endpoint</strong></p>\n<p>Once deployed, you can access the endpoint at <code class=\"language-text\">/api/hello</code> from your browser or via curl.</p>\n</li>\n</ol>\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/a7699dc85f24791de1e731ffb2050c35/914c7/Access-the-Endpoint.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: 20.253164556962027%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAECAYAAACOXx+WAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAv0lEQVQY022Py3KDMAxF2RuwYMHUEMzDFig80uya//+xm7HSZLro4o7kMxrJJ2uaBnlRwFqLIlUi0Lu3VlOW5Sf/MeVEqOsamR8mLAtjHEeIXOH7Hr0fsB27snmawJF1JoRZ2eA91nVBiBELM+YQ4H2PqqqQdZcOx3Fg2zY8Hj+4dC1c2+H7fgdzOjRg30+dkasgRAbHqAtXEdzOEyKC1rnXQue+YEyu3zbGgJIyEYo8/ygm/RR9J8U/ym9Ov8pP6CxnO5jss9YAAAAASUVORK5CYII='); background-size: cover; display: block;\"\n  ></span>\n  <img\n        class=\"gatsby-resp-image-image\"\n        alt=\"Access the Endpoint\"\n        title=\"Access the Endpoint\"\n        src=\"/static/a7699dc85f24791de1e731ffb2050c35/f058b/Access-the-Endpoint.png\"\n        srcset=\"/static/a7699dc85f24791de1e731ffb2050c35/c26ae/Access-the-Endpoint.png 158w,\n/static/a7699dc85f24791de1e731ffb2050c35/6bdcf/Access-the-Endpoint.png 315w,\n/static/a7699dc85f24791de1e731ffb2050c35/f058b/Access-the-Endpoint.png 630w,\n/static/a7699dc85f24791de1e731ffb2050c35/40601/Access-the-Endpoint.png 945w,\n/static/a7699dc85f24791de1e731ffb2050c35/914c7/Access-the-Endpoint.png 978w\"\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>This basic example demonstrates how to set up an endpoint quickly, without any additional configuration.</p>\n<h2 id=\"handling-http-methods-in-api-routes\" style=\"position:relative;\"><a href=\"#handling-http-methods-in-api-routes\" aria-label=\"handling http methods in api routes 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>Handling HTTP Methods in API Routes</strong></h2>\n<p>Next.js API Routes are versatile and can handle different HTTP methods (GET, POST, PUT, DELETE) within the same endpoint. You can implement logic based on the HTTP verb, by checking the <code class=\"language-text\">req.method</code> property.</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"46852418492037500000\"\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(`// pages/api/data.js\n\nexport default function handler(req, res) {\n  if (req.method === &quot;GET&quot;) {\n    // Handle GET request\n    res.status(200).json({ data: &quot;This is a GET response&quot; });\n  } else if (req.method === &quot;POST&quot;) {\n    // Handle POST request\n    const { name } = req.body;\n    res.status(201).json({ message: \\`Hello, \\${name}!\\` });\n  } else {\n    // Handle any other HTTP method\n    res.status(405).json({ error: &quot;Method Not Allowed&quot; });\n  }\n}`, `46852418492037500000`)\"\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=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token comment\">// pages/api/data.js</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> <span class=\"token keyword\">function</span> <span class=\"token function\">handler</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">req<span class=\"token punctuation\">,</span> res</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>req<span class=\"token punctuation\">.</span>method <span class=\"token operator\">===</span> <span class=\"token string\">\"GET\"</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token comment\">// Handle GET request</span>\n    res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">200</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> <span class=\"token literal-property property\">data</span><span class=\"token operator\">:</span> <span class=\"token string\">\"This is a GET response\"</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span> <span class=\"token keyword\">else</span> <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>req<span class=\"token punctuation\">.</span>method <span class=\"token operator\">===</span> <span class=\"token string\">\"POST\"</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token comment\">// Handle POST request</span>\n    <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> name <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> req<span class=\"token punctuation\">.</span>body<span class=\"token punctuation\">;</span>\n    res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">201</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> <span class=\"token literal-property property\">message</span><span class=\"token operator\">:</span> <span class=\"token template-string\"><span class=\"token template-punctuation string\">`</span><span class=\"token string\">Hello, </span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${</span>name<span class=\"token interpolation-punctuation punctuation\">}</span></span><span class=\"token string\">!</span><span class=\"token template-punctuation string\">`</span></span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span> <span class=\"token keyword\">else</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token comment\">// Handle any other HTTP method</span>\n    res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">405</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> <span class=\"token literal-property property\">error</span><span class=\"token operator\">:</span> <span class=\"token string\">\"Method Not Allowed\"</span> <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></code></pre></div>\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/8a731271fbf719ec0368383f7c359af2/d4c13/Handling-HTTP-Methods-in-API-Routes-data.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: 13.924050632911392%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAADCAIAAAAcOLh5AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAVUlEQVQI143Lyw2AIBAFQDoB3i77NZy9mEgV9t+JiQUQ5z7lXsvdRURUzcw9AGp9p9Y658zM4uejphZH6HCVwy11DML+06f0uAiNeDA6ExgQJgL6Dy9pDBlyO5elaAAAAABJRU5ErkJggg=='); background-size: cover; display: block;\"\n  ></span>\n  <img\n        class=\"gatsby-resp-image-image\"\n        alt=\"Handling HTTP Methods in API Routes data\"\n        title=\"Handling HTTP Methods in API Routes data\"\n        src=\"/static/8a731271fbf719ec0368383f7c359af2/f058b/Handling-HTTP-Methods-in-API-Routes-data.png\"\n        srcset=\"/static/8a731271fbf719ec0368383f7c359af2/c26ae/Handling-HTTP-Methods-in-API-Routes-data.png 158w,\n/static/8a731271fbf719ec0368383f7c359af2/6bdcf/Handling-HTTP-Methods-in-API-Routes-data.png 315w,\n/static/8a731271fbf719ec0368383f7c359af2/f058b/Handling-HTTP-Methods-in-API-Routes-data.png 630w,\n/static/8a731271fbf719ec0368383f7c359af2/d4c13/Handling-HTTP-Methods-in-API-Routes-data.png 825w\"\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><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/7e21e81b2239f26c51b14d194068b8a3/2ad15/Handling-HTTP-Methods-in-API-Routes-message.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: 15.822784810126581%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAADCAIAAAAcOLh5AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAW0lEQVQI143CwRHDIAwEQDohY8k6gdCBP/YnGffflStIJjtb7s/7vE7ZNgC7WWtNRF/f1VpFhKSqFndfi7GOMcmOGX5kc6jZr4CZ7UVUM5nsmZ2BHD7TRyD++ADKRBvgX38DkQAAAABJRU5ErkJggg=='); background-size: cover; display: block;\"\n  ></span>\n  <img\n        class=\"gatsby-resp-image-image\"\n        alt=\"Handling HTTP Methods in API Routes message\"\n        title=\"Handling HTTP Methods in API Routes message\"\n        src=\"/static/7e21e81b2239f26c51b14d194068b8a3/f058b/Handling-HTTP-Methods-in-API-Routes-message.png\"\n        srcset=\"/static/7e21e81b2239f26c51b14d194068b8a3/c26ae/Handling-HTTP-Methods-in-API-Routes-message.png 158w,\n/static/7e21e81b2239f26c51b14d194068b8a3/6bdcf/Handling-HTTP-Methods-in-API-Routes-message.png 315w,\n/static/7e21e81b2239f26c51b14d194068b8a3/f058b/Handling-HTTP-Methods-in-API-Routes-message.png 630w,\n/static/7e21e81b2239f26c51b14d194068b8a3/2ad15/Handling-HTTP-Methods-in-API-Routes-message.png 801w\"\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><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/acd3ecff42b2bcf549fbcac59adbb1bb/02cd5/Handling-HTTP-Methods-in-API-Routes-error.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: 15.18987341772152%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAADCAIAAAAcOLh5AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAW0lEQVQI14XJSw6EMAwE0ZwkIpEdd9sh4rMDwf2PNRr2iNLbVbru6zgPESUJwD1EdHov50x6RFeVVErpc4x1GTP3waVjGww3Z3tDqJk4W6q1gkE2MwX+nvcBjx/msxuPv5CrRAAAAABJRU5ErkJggg=='); background-size: cover; display: block;\"\n  ></span>\n  <img\n        class=\"gatsby-resp-image-image\"\n        alt=\"Handling HTTP Methods in API Routes error\"\n        title=\"Handling HTTP Methods in API Routes error\"\n        src=\"/static/acd3ecff42b2bcf549fbcac59adbb1bb/f058b/Handling-HTTP-Methods-in-API-Routes-error.png\"\n        srcset=\"/static/acd3ecff42b2bcf549fbcac59adbb1bb/c26ae/Handling-HTTP-Methods-in-API-Routes-error.png 158w,\n/static/acd3ecff42b2bcf549fbcac59adbb1bb/6bdcf/Handling-HTTP-Methods-in-API-Routes-error.png 315w,\n/static/acd3ecff42b2bcf549fbcac59adbb1bb/f058b/Handling-HTTP-Methods-in-API-Routes-error.png 630w,\n/static/acd3ecff42b2bcf549fbcac59adbb1bb/02cd5/Handling-HTTP-Methods-in-API-Routes-error.png 821w\"\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>This approach allows you to consolidate related functionality into one endpoint, keeping your API structure clean and maintainable.</p>\n<h2 id=\"dynamic-api-routes-in-nextjs\" style=\"position:relative;\"><a href=\"#dynamic-api-routes-in-nextjs\" aria-label=\"dynamic api routes 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>Dynamic API Routes in Next.js</strong></h2>\n<p>Dynamic API Routes allow you to create endpoints that respond to parameters in the URL, making your API more flexible and powerful.</p>\n<h3 id=\"using-dynamic-parameters\" style=\"position:relative;\"><a href=\"#using-dynamic-parameters\" aria-label=\"using dynamic parameters 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>Using Dynamic Parameters</strong></h3>\n<p>Create a dynamic route by naming your file with brackets. For instance, to handle requests for user-specific data:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"76679594665033970000\"\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(`// pages/api/user/[id].js\n\nexport default function handler(req, res) {\n  const { id } = req.query;\n\n  res.status(200).json({ userId: id, message: \\`User details for \\${id}\\` });\n}`, `76679594665033970000`)\"\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=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token comment\">// pages/api/user/[id].js</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> <span class=\"token keyword\">function</span> <span class=\"token function\">handler</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">req<span class=\"token punctuation\">,</span> res</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> id <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> req<span class=\"token punctuation\">.</span>query<span class=\"token punctuation\">;</span>\n\n  res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">200</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> <span class=\"token literal-property property\">userId</span><span class=\"token operator\">:</span> id<span class=\"token punctuation\">,</span> <span class=\"token literal-property property\">message</span><span class=\"token operator\">:</span> <span class=\"token template-string\"><span class=\"token template-punctuation string\">`</span><span class=\"token string\">User details for </span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${</span>id<span class=\"token interpolation-punctuation punctuation\">}</span></span><span class=\"token template-punctuation string\">`</span></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>Accessing <code class=\"language-text\">/api/user/123</code> would yield a response containing the user ID <code class=\"language-text\">123</code>.</p>\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/88ec00aa0836e9070f2f2600463def02/9f82e/Using-Dynamic-Parameters.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: 18.354430379746837%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAECAYAAACOXx+WAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAnklEQVQY022PywrCUAxE+xPupN5HkvusQtfS//+rI7dVKehimBDCyczUe6OUQl8WrCZqa/TeMTNCCDjn8N5/5YbfHNfsuTwFlyM1F1JKDNa0bRsqEVNF1Ug57w/OsOHn+QAfu+HzPNPeQSZVIbU75b5STUgqxBCQEIjB/yT07oAN/6Y+3UxmitWF8ljJJjRTiskON4l/Kg/Ykeyjc4sX++dxgv1QifwAAAAASUVORK5CYII='); background-size: cover; display: block;\"\n  ></span>\n  <img\n        class=\"gatsby-resp-image-image\"\n        alt=\"Using Dynamic Parameters\"\n        title=\"Using Dynamic Parameters\"\n        src=\"/static/88ec00aa0836e9070f2f2600463def02/f058b/Using-Dynamic-Parameters.png\"\n        srcset=\"/static/88ec00aa0836e9070f2f2600463def02/c26ae/Using-Dynamic-Parameters.png 158w,\n/static/88ec00aa0836e9070f2f2600463def02/6bdcf/Using-Dynamic-Parameters.png 315w,\n/static/88ec00aa0836e9070f2f2600463def02/f058b/Using-Dynamic-Parameters.png 630w,\n/static/88ec00aa0836e9070f2f2600463def02/9f82e/Using-Dynamic-Parameters.png 820w\"\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<h3 id=\"catch-all-api-routes\" style=\"position:relative;\"><a href=\"#catch-all-api-routes\" aria-label=\"catch all api routes 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>Catch-All API Routes</strong></h3>\n<p>To handle multiple dynamic segments, use the <code class=\"language-text\">[...]</code> syntax. For example:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"7251663560899768000\"\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(`// pages/api/user/[...params].js\n\nexport default function handler(req, res) {\n  const { params } = req.query;\n\n  res.status(200).json({ params, message: &quot;Catch-all API Route&quot; });\n}`, `7251663560899768000`)\"\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=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token comment\">// pages/api/user/[...params].js</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> <span class=\"token keyword\">function</span> <span class=\"token function\">handler</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">req<span class=\"token punctuation\">,</span> res</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> params <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> req<span class=\"token punctuation\">.</span>query<span class=\"token punctuation\">;</span>\n\n  res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">200</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> params<span class=\"token punctuation\">,</span> <span class=\"token literal-property property\">message</span><span class=\"token operator\">:</span> <span class=\"token string\">\"Catch-all API Route\"</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>Accessing <code class=\"language-text\">/api/user/profile/settings</code> returns an array of all segments.</p>\n<h2 id=\"middleware-in-api-routes\" style=\"position:relative;\"><a href=\"#middleware-in-api-routes\" aria-label=\"middleware in api routes 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>Middleware in API Routes</strong></h2>\n<p>Middleware functions in Next.js API Routes allow you to run custom logic before the main handler processes the request. This is useful for tasks such as logging and authentication.</p>\n<h3 id=\"implementing-custom-middleware\" style=\"position:relative;\"><a href=\"#implementing-custom-middleware\" aria-label=\"implementing custom 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>Implementing Custom Middleware</strong></h3>\n<p>You can add middleware by creating higher-order functions that wrap your handler. For instance, to log incoming requests:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"29413302129415910000\"\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(`// lib/logger.js\n\nexport function withLogger(handler) {\n  return async (req, res) => {\n    console.log(\\`Request received: \\${req.method} \\${req.url}\\`);\n    return handler(req, res);\n  };\n}`, `29413302129415910000`)\"\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=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token comment\">// lib/logger.js</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">function</span> <span class=\"token function\">withLogger</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">handler</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">return</span> <span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span><span class=\"token parameter\">req<span class=\"token punctuation\">,</span> res</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n    console<span class=\"token punctuation\">.</span><span class=\"token function\">log</span><span class=\"token punctuation\">(</span><span class=\"token template-string\"><span class=\"token template-punctuation string\">`</span><span class=\"token string\">Request received: </span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${</span>req<span class=\"token punctuation\">.</span>method<span class=\"token interpolation-punctuation punctuation\">}</span></span><span class=\"token string\"> </span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${</span>req<span class=\"token punctuation\">.</span>url<span class=\"token interpolation-punctuation punctuation\">}</span></span><span class=\"token template-punctuation string\">`</span></span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token keyword\">return</span> <span class=\"token function\">handler</span><span class=\"token punctuation\">(</span>req<span class=\"token punctuation\">,</span> res<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Then, use it in your API route:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"10351124575325344000\"\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(`// pages/api/hello.js\n\nimport { withLogger } from &quot;../../lib/logger&quot;;\n\nconst handler = (req, res) => {\n  res.status(200).json({ message: &quot;Hello with logging!&quot; });\n};\n\nexport default withLogger(handler);`, `10351124575325344000`)\"\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=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token comment\">// pages/api/hello.js</span>\n\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> withLogger <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">\"../../lib/logger\"</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">const</span> <span class=\"token function-variable function\">handler</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">(</span><span class=\"token parameter\">req<span class=\"token punctuation\">,</span> res</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n  res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">200</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> <span class=\"token literal-property property\">message</span><span class=\"token operator\">:</span> <span class=\"token string\">\"Hello with logging!\"</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> <span class=\"token function\">withLogger</span><span class=\"token punctuation\">(</span>handler<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div>\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/285dd0f8a0015e98b491467897900fd1/64d87/Implementing-Custom-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: 12.025316455696203%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAACCAYAAABYBvyLAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAU0lEQVQI132MwQ3AIAzEGCUhIRSaTEHf7L/NVSDxbB+WH5acnjEw54S7w8w2rbVtZgYRbX+xuqoiIiAiSESMnDOsO+oduIqgF4XXgm76Ozxt+fACRbI5PNuOGEMAAAAASUVORK5CYII='); background-size: cover; display: block;\"\n  ></span>\n  <img\n        class=\"gatsby-resp-image-image\"\n        alt=\"Implementing Custom Middleware\"\n        title=\"Implementing Custom Middleware\"\n        src=\"/static/285dd0f8a0015e98b491467897900fd1/f058b/Implementing-Custom-Middleware.png\"\n        srcset=\"/static/285dd0f8a0015e98b491467897900fd1/c26ae/Implementing-Custom-Middleware.png 158w,\n/static/285dd0f8a0015e98b491467897900fd1/6bdcf/Implementing-Custom-Middleware.png 315w,\n/static/285dd0f8a0015e98b491467897900fd1/f058b/Implementing-Custom-Middleware.png 630w,\n/static/285dd0f8a0015e98b491467897900fd1/64d87/Implementing-Custom-Middleware.png 818w\"\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<h3 id=\"using-third-party-middleware\" style=\"position:relative;\"><a href=\"#using-third-party-middleware\" aria-label=\"using third party 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>Using Third-Party Middleware</strong></h3>\n<p>For more advanced features, such as CORS, you can use third-party middleware packages. For example, to add CORS support</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"86984831821918520000\"\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(`// pages/api/cors.js\n\nimport Cors from &quot;cors&quot;;\n\n// Initializing the CORS middleware\nconst cors = Cors({\n  methods: [&quot;GET&quot;, &quot;HEAD&quot;],\n});\n\n// Helper method to wait for a middleware to execute before continuing\nfunction runMiddleware(req, res, fn) {\n  return new Promise((resolve, reject) => {\n    fn(req, res, (result) => {\n      if (result instanceof Error) {\n        return reject(result);\n      }\n      return resolve(result);\n    });\n  });\n}\n\nexport default async function handler(req, res) {\n  await runMiddleware(req, res, cors);\n  res.status(200).json({ message: &quot;CORS enabled&quot; });\n}`, `86984831821918520000`)\"\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=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token comment\">// pages/api/cors.js</span>\n\n<span class=\"token keyword\">import</span> Cors <span class=\"token keyword\">from</span> <span class=\"token string\">\"cors\"</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token comment\">// Initializing the CORS middleware</span>\n<span class=\"token keyword\">const</span> cors <span class=\"token operator\">=</span> <span class=\"token function\">Cors</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n  <span class=\"token literal-property property\">methods</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">[</span><span class=\"token string\">\"GET\"</span><span class=\"token punctuation\">,</span> <span class=\"token string\">\"HEAD\"</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">,</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token comment\">// Helper method to wait for a middleware to execute before continuing</span>\n<span class=\"token keyword\">function</span> <span class=\"token function\">runMiddleware</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">req<span class=\"token punctuation\">,</span> res<span class=\"token punctuation\">,</span> fn</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">return</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Promise</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">resolve<span class=\"token punctuation\">,</span> reject</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n    <span class=\"token function\">fn</span><span class=\"token punctuation\">(</span>req<span class=\"token punctuation\">,</span> res<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">(</span><span class=\"token parameter\">result</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n      <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>result <span class=\"token keyword\">instanceof</span> <span class=\"token class-name\">Error</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n        <span class=\"token keyword\">return</span> <span class=\"token function\">reject</span><span class=\"token punctuation\">(</span>result<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n      <span class=\"token punctuation\">}</span>\n      <span class=\"token keyword\">return</span> <span class=\"token function\">resolve</span><span class=\"token punctuation\">(</span>result<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">handler</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">req<span class=\"token punctuation\">,</span> res</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">await</span> <span class=\"token function\">runMiddleware</span><span class=\"token punctuation\">(</span>req<span class=\"token punctuation\">,</span> res<span class=\"token punctuation\">,</span> cors<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">200</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> <span class=\"token literal-property property\">message</span><span class=\"token operator\">:</span> <span class=\"token string\">\"CORS enabled\"</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><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/5284413e9763a992254b6538953cb2d0/baaa6/Using-Third-Party-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: 15.822784810126581%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAADCAYAAACTWi8uAAAACXBIWXMAAA7DAAAOwwHHb6hkAAAAiElEQVQI11WOQQ7CMAwE+xAgdkLtpCk9FNHy/48NSioVOKx2bUvjHd7bi33fcDdyyYxu1FoxN2KMiAiq2iUqSMsiXItyqUpKCTNjWRbcnaHWmee64qWSp5lixmMquI3/sJblgHVoEPQmBAn9nnPuBYYQjkUy7xpTxFLkHvUEnv7TUPr8fdY4zT+VmlUE5WtydAAAAABJRU5ErkJggg=='); background-size: cover; display: block;\"\n  ></span>\n  <img\n        class=\"gatsby-resp-image-image\"\n        alt=\"Using Third-Party Middleware\"\n        title=\"Using Third-Party Middleware\"\n        src=\"/static/5284413e9763a992254b6538953cb2d0/f058b/Using-Third-Party-Middleware.png\"\n        srcset=\"/static/5284413e9763a992254b6538953cb2d0/c26ae/Using-Third-Party-Middleware.png 158w,\n/static/5284413e9763a992254b6538953cb2d0/6bdcf/Using-Third-Party-Middleware.png 315w,\n/static/5284413e9763a992254b6538953cb2d0/f058b/Using-Third-Party-Middleware.png 630w,\n/static/5284413e9763a992254b6538953cb2d0/baaa6/Using-Third-Party-Middleware.png 813w\"\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>This ensures your API routes comply with cross-origin resource-sharing requirements.</p>\n<h2 id=\"error-handling-in-api-routes\" style=\"position:relative;\"><a href=\"#error-handling-in-api-routes\" aria-label=\"error handling in api routes 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>Error Handling in API Routes</strong></h2>\n<p>Robust error handling is crucial for providing meaningful responses and debugging issues. Next.js API Routes allow you to use try-catch blocks to manage errors gracefully.</p>\n<p>For example:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"78284252282523320000\"\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(`// pages/api/data.js\n\nexport default function handler(req, res) {\n  try {\n    // Simulate processing\n    if (!req.query.id) {\n      throw new Error(&quot;ID is required&quot;);\n    }\n\n    res.status(200).json({ data: &quot;Success&quot;, id: req.query.id });\n  } catch (error) {\n    console.error(&quot;Error occurred:&quot;, error);\n    res.status(500).json({ error: error.message });\n  }\n}`, `78284252282523320000`)\"\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=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token comment\">// pages/api/data.js</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> <span class=\"token keyword\">function</span> <span class=\"token function\">handler</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">req<span class=\"token punctuation\">,</span> res</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">try</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token comment\">// Simulate processing</span>\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>req<span class=\"token punctuation\">.</span>query<span class=\"token punctuation\">.</span>id<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token keyword\">throw</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Error</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"ID is required\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token punctuation\">}</span>\n\n    res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">200</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> <span class=\"token literal-property property\">data</span><span class=\"token operator\">:</span> <span class=\"token string\">\"Success\"</span><span class=\"token punctuation\">,</span> <span class=\"token literal-property property\">id</span><span class=\"token operator\">:</span> req<span class=\"token punctuation\">.</span>query<span class=\"token punctuation\">.</span>id <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    console<span class=\"token punctuation\">.</span><span class=\"token function\">error</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Error occurred:\"</span><span class=\"token punctuation\">,</span> error<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">500</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> <span class=\"token literal-property property\">error</span><span class=\"token operator\">:</span> error<span class=\"token punctuation\">.</span>message <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></code></pre></div>\n<p>Using patterns such as this improves the usability and reliability of your API.</p>\n<h2 id=\"testing-api-routes\" style=\"position:relative;\"><a href=\"#testing-api-routes\" aria-label=\"testing api routes 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>Testing API Routes</strong></h2>\n<p>Testing your API routes ensures they work as expected. You can use tools like Jest and Supertest for unit and integration testing.</p>\n<h3 id=\"for-example-using-jest-to-test-an-api-route\" style=\"position:relative;\"><a href=\"#for-example-using-jest-to-test-an-api-route\" aria-label=\"for example using jest to test an api route 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>For example: Using Jest to Test an API Route</strong></h3>\n<ol>\n<li>Install Jest and Supertest:</li>\n</ol>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"76877138858259230000\"\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(`npm install jest supertest --save-dev`, `76877138858259230000`)\"\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=\"sh\"><pre class=\"language-sh\"><code class=\"language-sh\">npm install jest supertest --save-dev</code></pre></div>\n<ol start=\"2\">\n<li>Create a test file:</li>\n</ol>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"13845767818495957000\"\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(`// __tests__/hello.test.js\n\nimport request from &quot;supertest&quot;;\nimport handler from &quot;../pages/api/hello&quot;;\n\ndescribe(&quot;GET /api/hello&quot;, () => {\n  it(&quot;should return a greeting message&quot;, async () => {\n    const req = {};\n\n    const res = {\n      status: jest.fn(() => res),\n      json: jest.fn(),\n    };\n\n    await handler(req, res);\n\n    expect(res.status).toHaveBeenCalledWith(200);\n    expect(res.json).toHaveBeenCalledWith({\n      message: &quot;Hello from Next.js API Routes!&quot;,\n    });\n  });\n});`, `13845767818495957000`)\"\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=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token comment\">// __tests__/hello.test.js</span>\n\n<span class=\"token keyword\">import</span> request <span class=\"token keyword\">from</span> <span class=\"token string\">\"supertest\"</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">import</span> handler <span class=\"token keyword\">from</span> <span class=\"token string\">\"../pages/api/hello\"</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token function\">describe</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"GET /api/hello\"</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token function\">it</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"should return a greeting message\"</span><span class=\"token punctuation\">,</span> <span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">const</span> req <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n\n    <span class=\"token keyword\">const</span> res <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token literal-property property\">status</span><span class=\"token operator\">:</span> jest<span class=\"token punctuation\">.</span><span class=\"token function\">fn</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> res<span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n      <span class=\"token literal-property property\">json</span><span class=\"token operator\">:</span> jest<span class=\"token punctuation\">.</span><span class=\"token function\">fn</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">}</span><span class=\"token punctuation\">;</span>\n\n    <span class=\"token keyword\">await</span> <span class=\"token function\">handler</span><span class=\"token punctuation\">(</span>req<span class=\"token punctuation\">,</span> res<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n    <span class=\"token function\">expect</span><span class=\"token punctuation\">(</span>res<span class=\"token punctuation\">.</span>status<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">toHaveBeenCalledWith</span><span class=\"token punctuation\">(</span><span class=\"token number\">200</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token function\">expect</span><span class=\"token punctuation\">(</span>res<span class=\"token punctuation\">.</span>json<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">toHaveBeenCalledWith</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n      <span class=\"token literal-property property\">message</span><span class=\"token operator\">:</span> <span class=\"token string\">\"Hello from Next.js API Routes!\"</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div>\n<ol start=\"3\">\n<li>Run your tests by using:</li>\n</ol>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"22991333780407476000\"\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(`npx jest`, `22991333780407476000`)\"\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=\"sh\"><pre class=\"language-sh\"><code class=\"language-sh\">npx jest</code></pre></div>\n<h3 id=\"integration-testing-with-nextjs-built-in-test-utilities\" style=\"position:relative;\"><a href=\"#integration-testing-with-nextjs-built-in-test-utilities\" aria-label=\"integration testing with nextjs built in test utilities 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>Integration Testing with Next.js’ Built-In Test Utilities</strong></h3>\n<p>Next.js comes with integrated support for testing, which helps streamline the process of validating your API routes in a more realistic,end-to-end scenario. For integration testing, you can use Next.js’ built-in utilities alongside Jest to simulate how your API routes work\nin the context of your full application. These utilities help set up a test environment that mimics production more closely than isolated unit tests.</p>\n<p>For example, you can create integration tests that use the Next.js server runtime to call your API routes and verify their behavior under\nconditions similar to real-world usage. Here’s a simplified example:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"78967557265842880000\"\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(`// __tests__/integration/hello.integration.test.js\n\nimport { createServer } from &quot;http&quot;;\nimport next from &quot;next&quot;;\nimport request from &quot;supertest&quot;;\n\nconst dev = process.env.NODE_ENV !== &quot;production&quot;;\nconst app = next({ dev });\nconst handle = app.getRequestHandler();\n\ndescribe(&quot;Integration Test for /api/hello&quot;, () => {\n  let server;\n\n  beforeAll(async () => {\n    await app.prepare();\n    server = createServer((req, res) => {\n      handle(req, res);\n    }).listen(3001);\n  });\n\n  afterAll(() => {\n    server.close();\n  });\n\n  it(&quot;should return a greeting message on GET /api/hello&quot;, async () => {\n    const res = await request(server).get(&quot;/api/hello&quot;);\n\n    expect(res.status).toBe(200);\n    expect(res.body).toEqual({ message: &quot;Hello from Next.js API Routes!&quot; });\n  });\n});`, `78967557265842880000`)\"\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=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token comment\">// __tests__/integration/hello.integration.test.js</span>\n\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> createServer <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">\"http\"</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">import</span> next <span class=\"token keyword\">from</span> <span class=\"token string\">\"next\"</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">import</span> request <span class=\"token keyword\">from</span> <span class=\"token string\">\"supertest\"</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">const</span> dev <span class=\"token operator\">=</span> process<span class=\"token punctuation\">.</span>env<span class=\"token punctuation\">.</span><span class=\"token constant\">NODE_ENV</span> <span class=\"token operator\">!==</span> <span class=\"token string\">\"production\"</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> app <span class=\"token operator\">=</span> <span class=\"token function\">next</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> dev <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token keyword\">const</span> handle <span class=\"token operator\">=</span> app<span class=\"token punctuation\">.</span><span class=\"token function\">getRequestHandler</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token function\">describe</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"Integration Test for /api/hello\"</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">let</span> server<span class=\"token punctuation\">;</span>\n\n  <span class=\"token function\">beforeAll</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">await</span> app<span class=\"token punctuation\">.</span><span class=\"token function\">prepare</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    server <span class=\"token operator\">=</span> <span class=\"token function\">createServer</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">req<span class=\"token punctuation\">,</span> res</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n      <span class=\"token function\">handle</span><span class=\"token punctuation\">(</span>req<span class=\"token punctuation\">,</span> res<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">listen</span><span class=\"token punctuation\">(</span><span class=\"token number\">3001</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n  <span class=\"token function\">afterAll</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n    server<span class=\"token punctuation\">.</span><span class=\"token function\">close</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n  <span class=\"token function\">it</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"should return a greeting message on GET /api/hello\"</span><span class=\"token punctuation\">,</span> <span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">const</span> res <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">request</span><span class=\"token punctuation\">(</span>server<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">\"/api/hello\"</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n    <span class=\"token function\">expect</span><span class=\"token punctuation\">(</span>res<span class=\"token punctuation\">.</span>status<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">toBe</span><span class=\"token punctuation\">(</span><span class=\"token number\">200</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n    <span class=\"token function\">expect</span><span class=\"token punctuation\">(</span>res<span class=\"token punctuation\">.</span>body<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">toEqual</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> <span class=\"token literal-property property\">message</span><span class=\"token operator\">:</span> <span class=\"token string\">\"Hello from Next.js API Routes!\"</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span></code></pre></div>\n<p>In this integration test:</p>\n<ul>\n<li>\n<p>The Next.js app is prepared and a real HTTP server is created by using <code class=\"language-text\">createServer</code>.</p>\n</li>\n<li>\n<p>The test makes an actual GET request to <code class=\"language-text\">/api/hello</code> on the server.</p>\n</li>\n<li>\n<p>The response status and body are validated.</p>\n</li>\n</ul>\n<p>This approach simulates a real-world scenario more closely than unit tests alone, ensuring that your API routes are properly integrated\nwithin the Next.js framework.</p>\n<p>Testing—both unit and integration—ensures that your API functions remain reliable as your application grows and evolves.</p>\n<h2 id=\"securing-nextjs-api-routes-with-supertokens\" style=\"position:relative;\"><a href=\"#securing-nextjs-api-routes-with-supertokens\" aria-label=\"securing nextjs api routes with supertokens 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>Securing Next.js API Routes with SuperTokens</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/9e2ba8940c8f1123465e76174989af40/d0c2f/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: 47.46835443037975%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAJCAIAAAC9o5sfAAAACXBIWXMAAAsTAAALEwEAmpwYAAABqElEQVQoz02PbW/aMBSFMy0kvo6d2InjkDgJBEJJeX8tpGzVoIxO2mhFK6H9LH7yBJGqPTrf7nmke7RR5n8r5Pdxp+x3eqHXj8Q0U+MsnOTJXRK24jAQnu8L3xdSSiGE53lFUVwul81mow1iPlRsrthK8bVy18qdKa/sNleDYpGn4+Iuz3Pf9wHwJwCg6zoAaJ3AHtbtpWKl4quQz+p81lBP8+nDbLaZjlaLxXA8aWYZIQT+w7qhxS7pSrsv7YGgA+G0GZnk7fPp/eP942m7/3N8fTm87LbbKKzr+leEACFU+QghzaVW5JCUWS1mtV163G1/7/fPP3avb6fz+e/pdHo7Hn8+734dDo9liTE2b1BKGGOahcGxsCA4oDi0rbaK+t1u7763XC4f16vyYb6YjsbDXt5qSF+gG7VaTcowa91rAIABCCAHg4OBAhIuD4MgjaMsVa0kakQyFJzbxDSMSjYMw+NuohpXGd0GQBUAauiSs0YcN5NrsjRhGByzVtUQArOmUz+V2UD7XF9hXo/G9RFicZtyhzJqWcgE0zCrBoCpf6HJKBge/gGUPjjwL5U6kAAAAABJRU5ErkJggg=='); background-size: cover; display: block;\"\n  ></span>\n  <img\n        class=\"gatsby-resp-image-image\"\n        alt=\"Supertokens\"\n        title=\"Supertokens\"\n        src=\"/static/9e2ba8940c8f1123465e76174989af40/f058b/Supertokens.png\"\n        srcset=\"/static/9e2ba8940c8f1123465e76174989af40/c26ae/Supertokens.png 158w,\n/static/9e2ba8940c8f1123465e76174989af40/6bdcf/Supertokens.png 315w,\n/static/9e2ba8940c8f1123465e76174989af40/f058b/Supertokens.png 630w,\n/static/9e2ba8940c8f1123465e76174989af40/40601/Supertokens.png 945w,\n/static/9e2ba8940c8f1123465e76174989af40/78612/Supertokens.png 1260w,\n/static/9e2ba8940c8f1123465e76174989af40/d0c2f/Supertokens.png 1362w\"\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 robust authentication and session management is crucial for protecting your API routes. <a href=\"https://supertokens.com/\" target=\"_blank\" rel=\"nofollow\">SuperTokens</a> offers a developer-friendly solution that enhances security while maintaining flexibility.</p>\n<h3 id=\"why-use-supertokens\" style=\"position:relative;\"><a href=\"#why-use-supertokens\" aria-label=\"why use supertokens 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>Why Use SuperTokens?</strong></h3>\n<p>SuperTokens simplifies session management and provides:</p>\n<ul>\n<li>\n<p><strong>Short-Lived Access Tokens and Rotating Refresh Tokens:</strong> Limit the window of opportunity for attackers by ensuring tokens expire quickly.</p>\n</li>\n<li>\n<p><strong>Token Theft Detection:</strong> Built-in mechanisms detect suspicious activity and revoke compromised tokens.</p>\n</li>\n<li>\n<p><strong>Customizable Authentication Flows:</strong> Easily integrate and tailor authentication processes to suit your needs.</p>\n</li>\n<li>\n<p><strong>High Scalability:</strong> Using JSON Web Tokens allows your system to handle large-scale applications without performance degradation.</p>\n</li>\n</ul>\n<h3 id=\"integrating-supertokens-into-api-routes\" style=\"position:relative;\"><a href=\"#integrating-supertokens-into-api-routes\" aria-label=\"integrating supertokens into api routes 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>Integrating SuperTokens into API Routes</strong></h3>\n<p>Example integration in a Node.js environment:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"32040389020074443000\"\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(`// pages/api/protected.js\n\nimport { verifySession } from &quot;supertokens-node/recipe/session&quot;;\n\nexport default async function handler(req, res) {\n  try {\n    // Verify user session using SuperTokens\n    await verifySession(req, res);\n\n    // Proceed if session is valid\n    res.status(200).json({ message: &quot;Authenticated request!&quot; });\n  } catch (error) {\n    res.status(401).json({ error: &quot;Unauthorized access&quot; });\n  }\n}`, `32040389020074443000`)\"\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=\"javascript\"><pre class=\"language-javascript\"><code class=\"language-javascript\"><span class=\"token comment\">// pages/api/protected.js</span>\n\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> verifySession <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">\"supertokens-node/recipe/session\"</span><span class=\"token punctuation\">;</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">handler</span><span class=\"token punctuation\">(</span><span class=\"token parameter\">req<span class=\"token punctuation\">,</span> res</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">try</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token comment\">// Verify user session using SuperTokens</span>\n    <span class=\"token keyword\">await</span> <span class=\"token function\">verifySession</span><span class=\"token punctuation\">(</span>req<span class=\"token punctuation\">,</span> res<span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n\n    <span class=\"token comment\">// Proceed if session is valid</span>\n    res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">200</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> <span class=\"token literal-property property\">message</span><span class=\"token operator\">:</span> <span class=\"token string\">\"Authenticated request!\"</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">;</span>\n  <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    res<span class=\"token punctuation\">.</span><span class=\"token function\">status</span><span class=\"token punctuation\">(</span><span class=\"token number\">401</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> <span class=\"token literal-property property\">error</span><span class=\"token operator\">:</span> <span class=\"token string\">\"Unauthorized access\"</span> <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></code></pre></div>\n<p>This setup ensures that only authenticated users can access protected API routes, thus enhancing the security of your backend operations.</p>\n<h2 id=\"optimizing-api-routes-for-performance\" style=\"position:relative;\"><a href=\"#optimizing-api-routes-for-performance\" aria-label=\"optimizing api routes for performance 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>Optimizing API Routes for Performance</strong></h2>\n<p>Performance is critical for user experience and scalability. Here are some strategies to optimize your Next.js API routes:</p>\n<h3 id=\"caching-strategies\" style=\"position:relative;\"><a href=\"#caching-strategies\" aria-label=\"caching strategies 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>Caching Strategies</strong></h3>\n<ul>\n<li>\n<p><strong>Server-Side Caching:</strong> Use caching mechanisms (like Redis) to store frequently requested data. This reduces load on your database and speeds up responses.</p>\n</li>\n<li>\n<p><strong>Static Generation:</strong> Where possible, pre-render static responses to reduce computation time.</p>\n</li>\n</ul>\n<h3 id=\"optimizing-database-queries\" style=\"position:relative;\"><a href=\"#optimizing-database-queries\" aria-label=\"optimizing database queries 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>Optimizing Database Queries</strong></h3>\n<ul>\n<li>\n<p><strong>Indexing:</strong> Ensure your database queries are optimized, by using proper indexing.</p>\n</li>\n<li>\n<p><strong>Query Optimization:</strong> Use efficient query patterns and limit data retrieval to only what is necessary.</p>\n</li>\n</ul>\n<h3 id=\"minimizing-api-payload-size\" style=\"position:relative;\"><a href=\"#minimizing-api-payload-size\" aria-label=\"minimizing api payload size 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>Minimizing API Payload Size</strong></h3>\n<ul>\n<li>\n<p><strong>Data Compression:</strong> Enable gzip compression for API responses.</p>\n</li>\n<li>\n<p><strong>Selective Fields:</strong> Return only essential data in your API responses to minimize payload size.</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>Next.js API Routes simplify backend development by allowing you to integrate serverless functions directly within your Next.js application. With built-in serverless support, seamless integration with the frontend, and simplified deployment, API Routes empower you to build robust backend functionality—without the need for separate servers or complex configurations.</p>\n<p>In this guide, we explored:</p>\n<ul>\n<li>\n<p><strong>What API Routes are</strong> and how they differ from traditional backend APIs.</p>\n</li>\n<li>\n<p><strong>How to set up your first API Route</strong>, handle HTTP methods, and create dynamic routes.</p>\n</li>\n<li>\n<p><strong>The role of middleware</strong> in logging, security, and request modification.</p>\n</li>\n<li>\n<p><strong>Error handling and testing</strong> techniques to ensure reliability.</p>\n</li>\n<li>\n<p><strong>Securing your API Routes with SuperTokens</strong> for robust session management and authentication.</p>\n</li>\n<li>\n<p><strong>Performance optimization strategies</strong> to ensure your API routes remain efficient and scalable.</p>\n</li>\n</ul>\n<p>By mastering Next.js API Routes and integrating advanced solutions like SuperTokens, you can build secure, high-performance backend functionality that scales with your application. Whether you’re building a small project or a large enterprise system, these techniques will help you manage requests efficiently, protect your data, and deliver a seamless user experience.</p>\n<p><strong><em>Embrace the power of Next.js API Routes to simplify your backend development while ensuring robust security and performance. Happy\ncoding!</em></strong></p>","frontmatter":{"date":"March 29, 2025","title":"Mastering Next.js API Routes: The Developer's Guide to Backend Functionality","cover":"mastering-nextjs-api-routes.png","author":"Mostafa Ibrahim","description":"Learn how to create and optimize API Routes in Next.js, handle requests effectively, and integrate authentication with SuperTokens for secure backend operations."},"fields":{"slug":"/mastering-nextjs-api-routes/"}},"site":{"siteMetadata":{"title":"SuperTokens Blog"}}},"pageContext":{"id":"b61409c1-0ff5-5cd3-985f-40be0d05c7df","fields__slug":"/mastering-nextjs-api-routes/","__params":{"fields__slug":"mastering-nextjs-api-routes"}}},
    "staticQueryHashes": []}