Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save andremalveira/0f47202e3b80e53094de167c02e0e817 to your computer and use it in GitHub Desktop.
Save andremalveira/0f47202e3b80e53094de167c02e0e817 to your computer and use it in GitHub Desktop.
Next.js - Hoc Client Side to authentication of page

✅ Next.js - Hoc Client Side to authentication of page

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 be false 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

app/hocs/pageWithAuth.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

app/pages/index.tsx

import type { NextPage } from 'next'
import PageWithAuth from 'hocs/pageWithAuth'

const Home: NextPage = () => {
  
  return (<>
    authenticated!
  </>)
}

export default PageWithAuth(Home)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment