title: How to set api routes if you want your NEXTJS app to follow a subdomain?
body: <p>I have set up a NEXTJS app that is under a subdomain and basically the structure is the following:</p>
  <p>/Pages-&gt;</p>
  <p>--/Sites</p>
  <p>--/api</p>
  <p>--/home</p>
  <p>--/subdomain_logic</p>
  <p>--_app.tsx</p>
  <p>...config files...</p>
  <p>As of this moment, if you go to <em>domain.com</em> you will be landing into another app that I developed so there is nothing configured outside of subdomain logic. If you go to <em>subdomain.domain.com</em> then you get all the logic ocurring into subdomain_logic. I want to set api routes but nextjs doesn't allow to set them outside of your <em>api</em> folder and if I leave them there those routes actually belong the <em>domain.com</em> app that I have in isolation. How would you create api routes on my situation?</p>
  <p>Here is my middleware.ts file:</p>
  <pre><code>import { NextRequest, NextResponse } from &quot;next/server&quot;;
  
  export const config = {
    matcher: [
      &quot;/&quot;,
      &quot;/([^/.]*)&quot;, // exclude `/public` files by matching all paths except for paths containing `.` (e.g. /logo.png)
      &quot;/site/:path*&quot;,
      &quot;/post/:path*&quot;,
      &quot;/_sites/:path*&quot;
    ]
  };
  
  export default function middleware(req: NextRequest) {
  
    const url = req.nextUrl;
  
    const pathname = req.nextUrl.pathname.toString();
  
    const hostname = req.headers.get(&quot;host&quot;);
  
    if (!hostname)
      return new Response(null, {
        status: 400,
        statusText: &quot;No hostname found in request headers&quot;
      });
  
    const currentHost =
      process.env.VERCEL_ENV === `production` ||
      process.env.VERCEL_ENV === `preview`
        ? 
          hostname
            .replace(`.domain.com`, &quot;&quot;)
            .replace(`${process.env.VERCEL_URL}`, &quot;&quot;)
            .replace(`${process.env.NEXT_PUBLIC_VERCEL_URL}`, &quot;&quot;)
        : hostname.replace(`.localhost:3000`, &quot;&quot;);
  
    if (pathname.startsWith(`/_sites`))
      return new Response(null, {
        status: 404
      });
  
    if (
      !pathname.includes(&quot;.&quot;)
    ) {
      if (currentHost === &quot;subdomain&quot;) {
        if (
          pathname === &quot;/login&quot; &amp;&amp;
          (req.cookies[&quot;next-auth.session-token&quot;] ||
            req.cookies[&quot;__Secure-next-auth.session-token&quot;])
        ) {
          url.pathname = &quot;/&quot;;
          return NextResponse.redirect(url);
        }
  
        url.pathname = `/subdomain${url.pathname}`;
        console.log(url);
        return NextResponse.rewrite(url);
      }
      url.pathname = `${pathname}`;
      return NextResponse.rewrite(url);
    }
  }
  </code></pre>
  <p>I would like to set up properly NextAuth if that give more clues into what could be the solution for my problem. Thanks for the help!</p>