⚠️ This lesson is retired and might contain outdated information.

Migrate Authentication From a Plain React App to a Gatsby App

Khaled Garbaya
InstructorKhaled Garbaya

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 2 years ago

Sometimes you need to protect some pages on your website and only shown to logged-in users. You can achieve this in Gatsby using a combination of client-only routes or Gatsby "Dynamic" Pages and reach router.

It becomes easier if you have already authentication in your plain react app and want to move it to Gatsby. In this lesson, you will learn how to reuse the authentication code you have in your existing plain React app in your Gatsby App

Instructor: [0:00] If we never get to one of our Gatsby client-only routes, you can see here we can still see the content without any authentications. Let's fix that. Let's go to our React app, and open up our index.js file. Inside of that, you can see here that we have these private routes and then with a component.

[0:26] Let's go to our app.js here. Instead of profiling stats, we need to use that private component. Let's go to component. Create a new file, call it private-route.js. We can go to the React app components, and then copy the code that we have in here.

[0:58] We already have reach router which is part of Gatsby. Here, we don't need to do anything extra. We have already the services off. Let's save.

[1:10] If we go here back to the index.js, you can see we are protecting these two routes, profile and stats. Let's copy this, go to our app.js, and replace both of them. Also, we need to add this login component. Let's add that, and look for the login component. It's here.

[1:46] Let's copy this, and go to our components in here. Then, add a new file, ccall it login.js, and we move the code in here. Hit save. Let's go to our app, and import login, and save. Now, it's time to go to our Gatsby app. Hit refresh, and go to profile.

[2:19] You can see here we have two errors we need to fix. We need to import the private route. Let's do that, and save. You can see here we are greeted by the login screen. If we put drawn and then the password, you can see here it's working.