Create a HOC (higher order component) for authentication in Next.js

You should separate and extract your authentication logic from getServerSideProps into a re-usable higher-order function.

For instance, you could have the following function that would accept another function (your getServerSideProps), and would redirect to your login page if the userToken isn’t set.

export function requireAuthentication(gssp) {
    return async (context) => {
        const { req, res } = context;
        const token = req.cookies.userToken;

        if (!token) {
            // Redirect to login page
            return {
                redirect: {
                    destination: '/admin/login',
                    statusCode: 302
                }
            };
        }

        return await gssp(context); // Continue on to call `getServerSideProps` logic
    }
}

You would then use it in your page by wrapping the getServerSideProps function.

// pages/index.js (or some other page)

export const getServerSideProps = requireAuthentication(context => {
    // Your normal `getServerSideProps` code here
})

Leave a Comment