Implement Auth Guards with Tokens throughout an Next.js App

Shadid Haque
InstructorShadid Haque
Share this video with your friends

Social Share Links

Send Tweet

Now that we have user Authentication, we can redirect users to sign in if we don't find a cookie to do so.

Throughout our app we can now replace our fauna token we have set in environment variables to the user token that we have access to.

[00:00] Let's go back to our actions dot JS file. Here, while setting the cookies, we're going to set an expiry date, and I'm going to make it 1 hour. [00:26] Next, in our home page, we're going to check for valid cookies. So I'm going to import cookies for the next header. We're gonna grab the token from the cookies, [00:49] And we're gonna check if the token exists. If there's no token, we're going to redirect to the sign in page. And let's go ahead and import redirect from next navigation. [01:10] Next, we're gonna replace the fauna key with the token. Now this will give a user read and write access because the user is now authenticated. So we're gonna do the same thing in our rooms page. [01:31] We'll import cookies from next headers, and then we'll try to retrieve the token from the cookies. We'll check if the token exists. If not, we'll redirect. And we'll replace the fauna [01:50] secret token. Now we can also pass the token to the message form component. And we will replace the fauna key with this token in the message form component. [02:11] Now we can do the same thing for message list component. We're just going to pass in the token. And in the message list, we'll use the token. [02:32] Now let's go back to the home page component again, and here we can pass in this token to the room list component. And in the room list component, we can just use this token. [02:56] Now back in the home page, we have a server action that is still using the fauna key. We can just use the token for this.