DarkianZ's avatar

Private Routes on Next JS ?

Hello everyone, im trying to learn next js as an old user coming from React, and i found myself struggling with 'how to set the private routes' . I've been reading across the web many solutions but can't seem to understand how to make them. Here is what i've got.

On react, i've got 1 file for the axios defaults and i usually put set my private routes on the app.js file.

This is my app.js file.

const [adminAuthenticated, setAdminAuthenticated] = useState(false);
  const [loading, setLoading] = useState(true);

  // Admin authentication
  useEffect(() => {
    axios.get(`/api/checkAuthenticated`).then((res) => {
      if (res.status === 200) {
        setAdminAuthenticated(true);
      }
      setLoading(false);
    });

    return () => {
      setAdminAuthenticated(false);
    };
  }, []);


  axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
    if (err.response.status === 401) {
      swal("Unauthorized", err.response.data.message, "warning");
      history.push('/getin');
    }
    return Promise.reject(err);
  });

  axios.interceptors.response.use(function (response) {
    return response;
  }, function (error) {
    if (error.response.status === 403)// acces denied
    {
      swal('Forbidden', error.response.data.message, "warning");
      history.push('403')
    }
    else if (error.response.status === 404)// page not found
    {
      swal('404 Error', "Url/Page Not Found", "warning");
      history.push('404')
    }
    return Promise.reject(error);
  }
  );




  let routes = (
    <>
      <Route exact path="/">
        <Home />
      </Route>
      <Route path="/login">
        <Login />
      </Route>
    </>
  );

  if (adminAuthenticated) {
    routes = (
      <>
        <Route exact path="/">
          <Home />
        </Route>

        <Route path="/login">
          <Login />
        </Route>

        <Route path="/admin" component={Admin} />
        <Route path="/comprador" component={Comprador} />
        <Route path="/vendedor" component={Vendedor} />
        <Route path="/usuario" component={Usuario} />

      </>
    );
  }

Here my axios-instance file.


import axios from "axios";

axios.defaults.baseURL = "http://localhost:8000/";
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.post['Accept'] = 'application/json';

axios.defaults.withCredentials = true;

axios.interceptors.request.use(function (config) {
  const token = localStorage.getItem('auth_token');
  config.headers.Authorization = token ? `Bearer ${token}` : '';
  return config;
});

export default axios;

Now on Next i've created a folder named components where i have two files. (axios-instance ) the same one above and (private-routes).

Here i show you the private-routes file on the next js folder.


import React from 'react';
import axios from './axios-instance';

const [adminAuthenticated, setAdminAuthenticated] = useState(false);
const [loading, setLoading] = useState(true);

// Admin authentication
useEffect(() => {
    axios.get(`/api/checkAuthenticated`).then((res) => {
        if (res.status === 200) {
            setAdminAuthenticated(true);
        }
        setLoading(false);
    });

    return () => {
        setAdminAuthenticated(false);
    };
}, []);


axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
    if (err.response.status === 401) {
        swal("Unauthorized", err.response.data.message, "warning");
        history.push('/getin');
    }
    return Promise.reject(err);
});

axios.interceptors.response.use(function (response) {
    return response;
}, function (error) {
    if (error.response.status === 403)// acces denied
    {
        swal('Forbidden', error.response.data.message, "warning");
        history.push('403')
    }
    else if (error.response.status === 404)// page not found
    {
        swal('404 Error', "Url/Page Not Found", "warning");
        history.push('404')
    }
    return Promise.reject(error);
}
);

Now at this point and dont know how to set my desired private routes for the files i want, i found on the web that i have to call the file (private-routes) in each file when im exporting them.

Any information will be helpful. Thanks for your time !! :D

0 likes
0 replies

Please or to participate in this conversation.