Sheeraz Shaikh
Bite Sized Learnings for Dev Community

Bite Sized Learnings for Dev Community

How to link a website to a specific URL path in NextJS

Redirecting a website to your own domain

In this blog post, I will share my knowledge on linking a standalone website to a specific URL path. This seems to be a very common use case but I had to struggle a bit to get this working for me, so I thought to write a blog post that might help a developer who is implementing the same use case.

Use Case

I have a web application hosted on Vercel using the NextJS framework (sheerazshaikh.com). Now I wanted to serve another application built using CRA (create-react-app) hosted on Vercel which could be accessed through a specific url path (sheerazshaikh.com/profile).

Problem

In order to link later application to a specific url, you need to write a module called Rewrite module in next.config.js file which will act as proxy and would not change the display url on browser. After doing a bit of research, it looked quite simple to write that module.

const PROFILE_URL = "YOUR_OWN_WEBSITE_URL";

module.exports = {
  async rewrites() {
    return  [
      {
        source: '/:path*',
        destination: `${PROFILE_URL}/:path*`,
      }
    ]
  }
}

This solution didn't work for me. It was downloading the initial HTML but all the assets associated were being failed to download

This is the screenshot of the error that I was facing.

image.png

By referring to the screenshot, the main page (profile) is loaded successfully, however other assets which help to render CRA (create-react-app) application are giving 404 because the request URL for all those assets is not referring to the accurate website as shown in this screenshot below

image.png

Solution

After thoroughly researching and analyzing the problem, I modified the next.config.js file in the following manner which worked for me.

const PROFILE_URL = "YOUR_OWN_WEBSITE_URL";

module.exports = {
  async rewrites() {
    return {
      fallback: [
      {
        source: '/:path*',
        destination: `${PROFILE_URL}/:path*`,
      }
    ]
    }
  }
}

By looking at the config file, you will get the idea that it will try to download everything (HTML and assets) from the primary website (in my case is sheerazshaikh.com), if it gets 404, then it will fall back to the actual URL which will download the accurate assets and the web application will work as expected.

Probably, this might not be an ideal solution and there would be areas for improvement, but this is the basic idea of how you can link a separate website into your own domain.

I hope this will help you if you are trying to serve another website through your domain.

Thanks for reading this blog post. That's it 🤟🏻!

 
Share this