Implementing private routes with React Router and Hooks

Ceci García García
Jun 17 · 3 min read
  • Private routes only accesible for authenticated users.
  • Auth data accesible from any component using React Context.

Initial setup

We create a simple React app with a common layout and a dynamic content that changes depending on the current route:

Providing the auth data to the components

No matter the authentication method your app is using, most probably you will need to store the auth data of the current user somewhere in the app, and some of your components will need to read from that data (our private routes, for example).

  • Provides access to the data to all its children.
  • Provides handlers to: store the auth data of a user just logged in, and remove the auth data of a user just logged out.

Defining private routes

Finally, we need to configure all our routes as private (only accesible for authenticated users) but the sign in page. To do so, we’ll implement a wrapper <PrivateRoute> for the <Route> components from React Router. The wrapper will make sure that the user is already authenticated before defining the matching component and render the sign in page if she isn’t:

Summing up

Implementing private routes is quite simple with React Router and React Context. There’re a lot of ways to do that, but I found this one specially focused and simple. I hope it helps!

Trabe

We are a development studio. We use Java, Rails, and JavaScript. This is where we write about the technologies we use at Trabe.

Thanks to David Barral.

Ceci García García

Written by

Software developer @trabe.

Trabe

Trabe

We are a development studio. We use Java, Rails, and JavaScript. This is where we write about the technologies we use at Trabe.