Vite JS Client Side Routing

I recently migrated from create-react-app to Vite because the initial startup and reload speeds are extremely fast. Vite helps me iterate faster on my project.

One major difference between Vite and create-react-app is that Vite does not do client side routing by default. In client side routing, any url you visit serves up your React App.tsx. You can then parse the urls in Javascript using React router and render the corresponding components for /profile or /login, etc.

Vite, however, will return a 404 for any url that’s not the root / url. So if you navigate to /profile you will get a 404 Not Found. To fix this, you can modify your vite.config.js file and serve your root App.tsx for any url matching a regex by adding the code below.

Note: You can’t serve the root for all paths /.* because your static assets will break. You will need to modify the regex to match your needs. My regex redirects all urls starting with @[number] to App.tsx because on shademap.app I permalink map locations, camera angles and times in the url like so /@47.6784,-122.1857,15z,1698422000851t,0b,0p,0m

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

const ClientSideRouting = {
  name: "dynamic-router",
  configureServer(server) {
    server.middlewares.use((req, res, next) => {
      if (req.url.search(/^\/@\d+/) !== -1) {
        req.url = "/";
      }
      next();
    });
  },
};

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), ClientSideRouting],
  server: {
    port: 3000,
  },
});

The port: 3000 configuration is optional, but you’ll recognize it as following the convention set by create-react-app. What can I say, change is hard.

 
10
Kudos
 
10
Kudos

Now read this

What’s up with tree shaking?

Me when I found out how tree shaking really works I’m willing to bet you have a lot of “dead” code in your webpack bundles. I used to think unused code was magically excluded by webpack but it turned out I was wrong. Oh the woe for slow... Continue →