Setting Up Auth Guards with React Router

Jacob Short
Jan 5 · 2 min read

Rendering certain routes or pages based on a user’s authentication is important and that’s why I was surprised to see that my googling lead to less than satisfactory results when it comes to authentication guards in React. Sometimes you just need a better understanding (or vocabulary) to harness the powers of the google and React. React router has this example. This is fine. They utilize useAuth. I find it a tad bit hard to follow for a tutorial, however, because it can be even simpler! Here’s how:

state = {    auth: false};

Boom. And we’re done! Congrats!

Image for post
Image for post

Ok, there’s a bit more.

{ this.state.auth ? <SomeComponent /> : <h1>Please login!</h1> }

You can use a ternary expression in your component’s JSX! So this only renders <SomeComponent /> when this.state.auth is ‘true’. We set auth to true for successful login requests from our server like so:

.then(res => res.json())
.then(json => this.setState({ auth: true }));

This is assuming you throw an error anytime that the login is unsuccessful. That’s really all there is to simple authentication and conditional rendering. When the user is not logged in or logs out, you simply use this.setState({ auth: false }).

Now, there are other ways to do this as well. When using rails, you can set up a before_action in controllers that checks if a user is logged in before any methods are invoked. You can see more here. You would still need error handling on the frontend so this is a bit more work overall. The whole idea of this programming thing is to code as little as possible. If you have other resources, please comment below!

Also, thanks Arya Muali for this wonderful post.

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store