Search code examples
javascriptreact-routersockjs

Prevent React Router from routing a server API path


On the server an API only path has been set under /api.

When calling this path on the client-side, react-router takes over and responds with:

browser.js:49 Warning: [react-router] Location "/api/my_request" did not match any routes

How can we tell react-router to bypass this and just send the request out to the server?

Update:

This is how the request is being sent:

const sock = new SockJS('http://localhost:3030/api')

sock.onopen = () => {
  console.log('open')
}
sock.onmessage = (e) => {
  console.log('message', e.data)
}
sock.onclose = () => {
  console.log('close')
}

sock.send('test')

Solution

  • Here is how I bypass React Router for my API routes with React Router 4.

    I had to remember that React Router is in a React component. We can use JavaScript within it and we can test the URL.

    In this case, I check for /api/ in the pathname of the URL. If it exists, then I do nothing and skip React Router entirely. Else, it has a route that does not begin with /api/ and I let React Router handle it.

    Here is my App.js file in my client folder:

    import React from 'react'
    import Home from './components/Home'
    import AnotherComponent from './components/AnotherComponent'
    import FourOhFour from './components/FourOhFour'
    import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
    
    export default function App() {
       const api_regex = /^\/api\/.*/
       // if using "/api/" in the pathname, don't use React Router
       if (api_regex.test(window.location.pathname)) {
          return <div /> // must return at least an empty div
       } else {
          // use React Router
          return (
             <Router>
                <div className="App">
                   <Switch>
                      <Route exact path="/" component={Home} />
                      <Route exact path="/another-link" component={AnotherComponent} />
                      <Route component={FourOhFour} />
                   </Switch>
                </div>
             </Router>
          )
       }
    }