Kushagra Chopra
Kushagra Chopra

Reputation: 3

React router V6 only working for root path

This is how I have my code set up in my App.jsx file:

export const App = () => {
    return (<>
        <Router>
            <Routes>
                <Route path="/" element={<Home/>} />
                <Route path="/account" element={<MyAccount/>} />
            </Routes>
        </Router>
    </>)
}

When I run my react app on my local snowpack server it will correctly load in the home component when I go to http://localhost:8080. However, when I go to http://localhost:8080/account Chrome says:

This localhost page can’t be found

No webpage was found for the web address: http://localhost:8080/account

HTTP ERROR 404

Does anyone have any thoughts?

Update 1

I modified the DEFAULT_CONFIG variable in the config.js file for snowpack as shown below but I'm still having the same issue. Is this the correct way to do this?

//in node_modules/snowpack/lib/config.js
...
const DEFAULT_CONFIG = {
    ...
    routes: [
        {
            "match": 'routes',
            "src": '.*',
            "dest": '/index.html',
        },
    ],
}

Resolution

I created a separate file in the root folder of my app called snowpack.config.mjs and added the code below

// in snowpack.config.mjs
export default {
    routes: [
        {
        match: 'routes',
        src: '.*',
        dest: '/index.html',
        },
    ],
};

Upvotes: 0

Views: 1703

Answers (1)

Rafael Dowling Goodman
Rafael Dowling Goodman

Reputation: 913

This is a pretty typical problem for client-side routing (the server is unaware of valid client-side routes).

Typically, you'd define fallback routes on the server to take the client back to index.html where client-side routing can do its thing.

For Snowpack:

// snowpack.config.mjs
export default {
  routes: [
    {
      match: 'routes',
      src: '.*',
      dest: '/index.html',
    },
  ],
};

See https://www.snowpack.dev/guides/routing#scenario-1-spa-fallback-paths

Note that when you push to production, you'll have to do the equivalent for whatever server is hosting your app.

Upvotes: 1

Related Questions