title: How do I protect routes on my front end with Passport.js and Axios?
body: <p>I am a bit confused with react-router-dom v6 and using passport.js for protecting my routes. I have a session established with passport.js, however, I am not sure how to set up protected routes with authentication from Passport.js.</p>
  <p>My login page calls the following function when the submit button is pressed:</p>
  <pre><code>    e.preventDefault();
  
      login(data)
        .then((response) =&gt; {
          toast.success(response.data.message);
          setData({ username: &quot;&quot;, password: &quot;&quot; });
          navigate(&quot;/dashboard&quot;);
        })
        .catch((err) =&gt; {
          if (err.response) {
            toast.error(err.response.data.message);
          } else if (err.request) {
            toast.error(err.request);
          } else {
            toast.error(err.message);
          }
        });
    };
  </code></pre>
  <p>This calls the login() function, which is contained in my loginAPI.js file on my front end.</p>
  <pre><code>
  const instance = axios.create({
    baseURL: &quot;http://localhost:8000/api/&quot;,
    timeout: 1000,
    withCredentials: true,
  });
  
  export async function login(data) {
    if (!data.username || !data.password) {
      return Promise.reject(new Error(&quot;Data is missing&quot;));
    }
  
    return await instance.post(&quot;/login&quot;, data);
  }
  </code></pre>
  <p>Which in turn calls my login.js file in my routes/api folder on my back end.</p>
  <pre><code>var passport = require(&quot;passport&quot;);
  
  router.post(
    &quot;/login&quot;,
    passport.authenticate(&quot;local&quot;, {
      failureRedirect: &quot;/login-failure&quot;,
      successRedirect: &quot;/login-success&quot;,
    })
  );
  
  module.exports = router;
  </code></pre>
  <p>Everything authenticates properly, and redirects me to /dashboard upon authentication from Passport, however, that is due to the <code>navigate(&quot;/dashboard&quot;);</code> in my handleOnSubmit function. I can still access my dashboard without having to login as my app.js file is set up as follows:</p>
  <pre><code>import Login from &quot;./pages/Login&quot;;
  import { BrowserRouter as Router, Routes, Route } from &quot;react-router-dom&quot;;
  
  function App() {
    return (
      &lt;div&gt;
        &lt;Router&gt;
          &lt;Routes&gt;
            &lt;Route exact path=&quot;/&quot; element={&lt;Login /&gt;} /&gt;
            &lt;Route path=&quot;/login&quot; element={&lt;Login /&gt;} /&gt;
            &lt;Route path=&quot;/dashboard&quot; element={&lt;Dashboard /&gt;} /&gt;
          &lt;/Routes&gt;
        &lt;/Router&gt;
      &lt;/div&gt;
    );
  }
  
  export default App;
  </code></pre>
  <p>How would I protect the dashboard route if the user hasn't logged/been authenticated with react-router-dom v6? Thanks!</p>