Naman Arora

How to make a Protected Route in Next Js ?

Pushlished on 06 Feb 2023

Create a Next js application

With npx

$ npx create-next-app myapp

With npx(Typescript)

$ npx create-next-app myapp --ts

or

With yarn

$ yarn create next-app myapp

With yarn(Typescript)

$ npx create-next-app myapp --ts

Create an IsAuth component

in components src/components/isAuth.tsx

import React from 'react';
import { useRouter } from 'next/router';

function IsAuth<T>(Component: React.ComponentType<T>) {
    return (props: T) => {
        // make a api call to check if user is authenticated
        const { data, loading, error } = useMeQuery();
        const router = useRouter();

        if (loading) {
            return <div>Loading...</div>;
        }

        if (error || !data) {
            router.push('/login');
        }

        return (
            <>
                <Component {...props!} />
            </>
        );
    };
}

export default IsAuth;

This is a higher order component (HOC) learn more about it from react docs.

Using IsAuth on a Protected route

Now we can use this component in src/pages/index.tsx

import { NextPage } from 'next';
import Head from 'next/head';
import IsAuth from '../components/IsAuth';

const Index: NextPage = () => {
    return (
        <div>
            <h1>My protected route</h1>
        </div>
    );
};

export default IsAuth(Index);

Now this page is protected route it will redirect the user to login page if the user is not authenticated.