A simple client side Hoc for Next.js, in this example I use 'isAuthenticated' cookies as verification, if user authenticate it will be set to
true
if cookie does not exist it will befalse
and user is redirected to/login
.
Um Hoc simples do lado do cliente para Next.js, neste exemplo eu uso cookies 'isAuthenticated' como verificação, se o usuário autenticar será definido como
true
se o cookie não existir seráfalse
e o usuário será redirecionado para/login
.
app
├──📁 hocs
│ └── pageWithAuth.tsx
├──📁 pages
│ ├── _app.tsx
│ └── index.tsx
import type { NextPage } from "next";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { parseCookies } from 'nookies'
const PageWithAuth = (Component:NextPage) => {
const AuthenticatedComponent = () => {
const router = useRouter();
const cookies = parseCookies()
const isAuthenticated = !cookies.isAuthenticated ? false : JSON.parse(cookies.isAuthenticated)
const [ isAuth, setIsAuth ] = useState(false)
useEffect(() => {
const getUser = async () => {
if (!isAuthenticated) {
router.push('/login');
} else {
setIsAuth(true)
}
};
getUser();
}, [isAuthenticated, router]);
return !!isAuth ? <Component /> : null; // Render whatever you want while the authentication occurs
};
return AuthenticatedComponent;
};
export default withAuth
import type { NextPage } from 'next'
import PageWithAuth from 'hocs/pageWithAuth'
const Home: NextPage = () => {
return (<>
authenticated!
</>)
}
export default PageWithAuth(Home)