Skip to content

Instantly share code, notes, and snippets.

@ArnabXD
Last active April 21, 2022 15:53
Show Gist options
  • Save ArnabXD/948651428c62d52e87a03747477e16f8 to your computer and use it in GitHub Desktop.
Save ArnabXD/948651428c62d52e87a03747477e16f8 to your computer and use it in GitHub Desktop.
NextJS+TypeScript+FC Authentication HOC example

NextJS TypeScript Higher Order Functional Component

import { useState, useEffect, FC } from 'react';
import { useRouter } from 'next/router';

export const withAuth = <P extends object>(C: FC<P>) => {
    return (props: P) => {
        const router = useRouter();
        useEffect(() => {
            const token = window.localStorage.getItem("token");
	    // Authentication Checking ...
            fetch('/validate', {
                method: 'post',
                body: JSON.stringify({ token })
            }).then(res => {
                if (res.status !== 200) {
                    router.replace("/login")
                }
            })
        }, [])
        return <C {...props} />
    }
}

Additionally a useState can be used to conditionally show Preloading skeleton while auth checking

@joshuaolusayo
Copy link

Thank you. It's quite helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment