<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Baraky on Medium]]></title>
        <description><![CDATA[Stories by Baraky on Medium]]></description>
        <link>https://medium.com/@jfbaraky?source=rss-41f9b3382520------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-qOxeVF-iKDddp09gZdH1w.jpeg</url>
            <title>Stories by Baraky on Medium</title>
            <link>https://medium.com/@jfbaraky?source=rss-41f9b3382520------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 12:53:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jfbaraky/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using wildcard subdomains as paths on Next.js]]></title>
            <link>https://medium.com/@jfbaraky/using-subdomains-as-paths-on-next-js-e5aab5c28c28?source=rss-41f9b3382520------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5aab5c28c28</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Baraky]]></dc:creator>
            <pubDate>Tue, 14 Feb 2023 17:42:24 GMT</pubDate>
            <atom:updated>2023-02-15T17:29:30.194Z</atom:updated>
            <content:encoded><![CDATA[<p>From time to time, here at <a href="https://www.appmasters.io/en">App Masters</a>, we need to work on a project with a wildcard subdomain with a different theme (or data) for each one of the of the possible subdomains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l0JqKFQ03UHwQqcqgIVLWw.jpeg" /></figure><p>Since we’re using <a href="https://nextjs.org/">Next.js</a>, this looks like something that should be possible out-of-the-box, but it’s not that simple.</p><p>On the client side, we can easily know the subdomain using the window.location , but on server side, it’s only possible to know it on the runtime and not on build time, so we had to give up the static rendering and some other optimization features Next.js made available, in favor of always use a getServerSideProps and get the subdomain inside the request.</p><p><strong>NOT ANYMORE!</strong></p><p>My first approach trying to handle this issue was to map the requests trying to use the Next.js rewrite function watching the header of each request. It makes sense to work, but for now, we can’t map header values as routes, only parameters.</p><p>Other solution is to have a custom node server, serving the Next.js frontend, but you will miss some of the optimization features and will have more code to maintain.</p><h3>The solution: Using middleware!</h3><p>Introduced on Next 12 and updated on Next 13, we can now easily have a <a href="https://nextjs.org/docs/advanced-features/middleware">middleware</a> that will handle all our requests to the next node server and we can use this to change the request before it gets to the router.</p><p>So first, I created a folder inside my /src/pages folder, called [subdomain] and added all my pages on this folder. You probably already know about this, but adding the [] on the folder/file name inside the page folder, will make it dynamic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*aFc9dSnCyyoH9eDObnZJ5g.png" /><figcaption>This is how we can get dynamic routing on Next.js</figcaption></figure><p>After this, I’ve created the file src/middleware.ts (it need to be on the same level as the pages folder) and started to write some code:</p><pre>// middleware.ts<br>import { NextResponse } from &#39;next/server&#39;;<br>import type { NextRequest } from &#39;next/server&#39;;<br>import { getValidSubdomain } from &#39;@/utils/subdomain&#39;;<br><br>// RegExp for public files<br>const PUBLIC_FILE = /\.(.*)$/; // Files<br><br>export async function middleware(req: NextRequest) {<br>  // Clone the URL<br>  const url = req.nextUrl.clone();<br><br>  // Skip public files<br>  if (PUBLIC_FILE.test(url.pathname) || url.pathname.includes(&#39;_next&#39;)) return;<br><br>  const host = req.headers.get(&#39;host&#39;);<br>  const subdomain = getValidSubdomain(host);<br>  if (subdomain) {<br>    // Subdomain available, rewriting<br>    console.log(`&gt;&gt;&gt; Rewriting: ${url.pathname} to /${subdomain}${url.pathname}`);<br>    url.pathname = `/${subdomain}${url.pathname}`;<br>  }<br><br>  return NextResponse.rewrite(url);<br>}</pre><p>The exported function middleware will handle all my requests and check if it have a valid subdomain. If it have, I’ll manually rewrite the pathname to the /{subdomain} . So, a request on https://baraky.domain.com/edit will access the page for https://baraky.domain.com/baraky/edit .</p><p>Here’s the code for the getValidSubdomain :</p><pre>export const getValidSubdomain = (host?: string | null) =&gt; {<br>  let subdomain: string | null = null;<br>  if (!host &amp;&amp; typeof window !== &#39;undefined&#39;) {<br>    // On client side, get the host from window<br>    host = window.location.host;<br>  }<br>  if (host &amp;&amp; host.includes(&#39;.&#39;)) {<br>    const candidate = host.split(&#39;.&#39;)[0];<br>    if (candidate &amp;&amp; !candidate.includes(&#39;localhost&#39;)) {<br>      // Valid candidate<br>      subdomain = candidate;<br>    }<br>  }<br>  return subdomain;<br>};</pre><p>I’ve added some other features to the function, to be able to get the subdomain even if the host string is not available.</p><p>Now you will be able to change your pages inside the [subdomain] folder. The subdomain value will be available inside your router, on the query parameters and you can use this how you want:</p><ul><li>Fetch the data relative for each subdomain</li><li>Have a different theme for each subdomain</li><li>Have specific cache for each subdomain, and a static generate page using getStaticProps</li></ul><p>But remember: to have access to the wildcard subdomain, you’ll need to host your Next.js app inside a hosting that provides this feature.</p><h3>Why is this relevant?</h3><p>Having all your pages separated on a sub-route instead of a subdomain will allow you to use getStaticProps for each one of the subdomains, since you’ll be able to separate then on different caches. Without it, Next.js will not be able to differentiate https://something.domain.com from https://other-thing.domain.com , returning the same static render for each website.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5aab5c28c28" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>