Fixing React Router Gotcha on Netlify and Vercel

🚀 A Crucial React Router Gotcha Most Developers Don't Know 🚨 If you're building a React app with React Router, there's a common issue many developers don't realize, especially after deploying to platforms like Netlify, Vercel, etc. You test your app locally, and everything works fine. Clicking through nav menus? Everything loads perfectly. So you think: "Looks good to go!" But here's the catch ⚠️ Try manually refreshing a route like /about, /contact, or any deep link other than /… on the production site. 💥 You might get a 404 - Page Not Found error! Why? Because when you hit refresh, the request goes directly to the server, and by default, most static hosting services don’t know how to handle client-side routes. How to Fix It👇 𝗙𝗼𝗿 𝗡𝗲𝘁𝗹𝗶𝗳𝘆: Create a _redirects file in your public folder with this line: /* /index.html 200 𝗙𝗼𝗿 𝗩𝗲𝗿𝗰𝗲𝗹: Add a file with the name vercel.json inside your project root with the following code: { "rewrites": [ { "source": "/(.*)", "destination": "/" } ] } This tells the server to always serve index.html for any route that does not exist or the server is not able to render, letting React Router, which is code in the index.html do its job even after a refresh. So always do page refresh testing for routes other than / route after deployment. Local testing can be misleading because your dev server already handles routing. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. 𝗣𝗦: Recording of yesterday's 3 hours webinar "𝗟𝗲𝗮𝗿𝗻 𝗧𝗼 𝗕𝘂𝗶𝗹𝗱 𝗔 𝗙𝘂𝗹𝗹𝘀𝘁𝗮𝗰𝗸 𝗛𝗼𝘁𝗲𝗹 𝗕𝗼𝗼𝗸𝗶𝗻𝗴 𝗔𝗽𝗽 𝗨𝘀𝗶𝗻𝗴 𝗟𝗼𝘃𝗮𝗯𝗹𝗲 𝗔𝗜 + 𝗖𝗹𝗮𝘂𝗱𝗲 𝗖𝗼𝗱𝗲" is uploaded and is available to watch. #javascript #reactjs #webdevelopment

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories