Wednesday, February 7, 2024

Sitecore XM Cloud - Fixing URL Redirections in Next.js on Vercel Using vercel.json

When URLs don't redirect correctly, it can be frustrating. Recently, we faced this challenge in our Next.js app on Vercel. Let's walk through how we tackled it.

Our URLs containing spaces or special characters weren't redirecting properly on Vercel. This glitch disrupted our users' flow and needed fixing ASAP.

Exploring Solutions:

At first, we tried a JavaScript-based approach within our app code. It worked fine locally but didn't cut it on Vercel.

Leveraging vercel.json:

Next, we discovered Vercel's powerful vercel.json file. With it, we could define redirect rules to map old URLs to new ones. Simple yet effective!

Crafting the Solution:

We created a vercel.json file with rewrite rules. These rules told Vercel how to handle URLs with spaces or special characters, ensuring they redirected correctly.


Sample vercel.json Code:


{
    "rewrites": [
      {        
        "source": "/(.*)%20(.*)",
        "destination": "/$1-$2"
      },
      {        
        "source": "/(.*)\\s(.*)",
        "destination": "/$1-$2"
      }
    ]
  }
 

Deployment and Validation:

After updating the vercel.json file, we deployed our Next.js app on Vercel. Through testing, we confirmed that our URLs now redirected smoothly, no more hiccups!

Conclusion:

In our journey to fix URL redirection issues, we learned the power of vercel.json. By leveraging its capabilities, we resolved our problem and improved our users' experience. It's a reminder that sometimes, simple solutions are the best.

No comments:

Post a Comment