Skip to content

Instantly share code, notes, and snippets.

@usmanity
Last active December 15, 2022 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save usmanity/4848b7a6cc980b6df37244c1e095db54 to your computer and use it in GitHub Desktop.
Save usmanity/4848b7a6cc980b6df37244c1e095db54 to your computer and use it in GitHub Desktop.

Session Checker

This component can be used on any page where you want to check if a user is logged in.

If not logged in, they will be redirected to the login page.

The useEffect hook waits until things are ready before checking the session status

I use this in next.js apps but it might work in react apps with slight modifications.

import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
import { useEffect } from "react";
export default function SessionChecker() {
const { status } = useSession();
const router = useRouter();
useEffect(() => {
if (status === "unauthenticated") {
router.push("/login");
}
});
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment