Created Protected Routes In Next.js Using Next-Auth
Hello Guuys! Today I 'Il show you how to create Protected Routes In Next.js using Next-Auth.
first go to app.js and define Auth function is a wrapper component that we're going to use inside my app it accept a children and inside this function we use useSession Hook from Next-Auth and set required to true only logged in use can access to it and for onUnauthenticated redirect user to unauthorized page and we need to implemented and the check the status in the useSession if it loading show loading and if it's not loading show children
function Auth({ children }) {
const router = useRouter();
const { status } = useSession({
required: true,
onUnauthenticated() {
router.push("/unautorized");
},
});
if (status === "loading") {
return <div>Loading...</div>;
}
return children;
}
inside pages folder create a new page unauthorized page
import Layout from '../components/Layout';
export default function Unauthorized() {
return (
<Layout title="Unauthorized Page">
<h1 className="text-xl">Access Denied</h1>
</Layout>
);
}
then let's use Auth function inside myApp
import { SessionProvider, useSession } from "next-auth/react";
import "../styles/globals.css";
import { StoreProvider } from "../utils/Store";
import { useRouter } from "next/router";
function MyApp({ Component, pageProps: { session, ...pageProps } }) {
return (
<SessionProvider session={session}>
<StoreProvider>
{Component.auth ? (
<Auth>
<Component {...pageProps} />
</Auth>
) : (
<Component {...pageProps} />
)}
</StoreProvider>
</SessionProvider>
);
}
function Auth({ children }) {
const router = useRouter();
const { status } = useSession({
required: true,
onUnauthenticated() {
router.push("/unautorized");
},
});
if (status === "loading") {
return <div>Loading...</div>;
}
return children;
}
export default MyApp;
Go to the page that we want to protected at the end
import Layout from '../components/Layout';
const ShippingCartPage = () => {
return (
<Layout title="Shipping Cart">
<h1 className="text-xl">Shipping Cart</h1>
</Layout>
)
}
ShippingCartPage.auth = true;
export default ShippingCartPage;
I hope this post helps!
Subscribe to my newsletter
Read articles from Said Mounaim directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Said Mounaim
Said Mounaim
Hi There, i'm Said Mounaim A passionate Intermediate Full Stack Developer having an experience of building responsive Web applications with JavaScript / React.js / Next.js / Node.js and some other cool libraries and frameworks.