Skip to content

Instantly share code, notes, and snippets.

@alieslamifard
Last active May 31, 2023 20:10
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save alieslamifard/dd81ce85e20dc47c57ed6825ff153288 to your computer and use it in GitHub Desktop.
Save alieslamifard/dd81ce85e20dc47c57ed6825ff153288 to your computer and use it in GitHub Desktop.
Private route HOC for Next.js
import React from 'react';
import Router from 'next/router';
const login = '/login?redirected=true'; // Define your login route address.
/**
* Check user authentication and authorization
* It depends on you and your auth service provider.
* @returns {{auth: null}}
*/
const checkUserAuthentication = () => {
return { auth: null }; // change null to { isAdmin: true } for test it.
};
export default WrappedComponent => {
const hocComponent = ({ ...props }) => <WrappedComponent {...props} />;
hocComponent.getInitialProps = async (context) => {
const userAuth = await checkUserAuthentication();
// Are you an authorized user or not?
if (!userAuth?.auth) {
// Handle server-side and client-side rendering.
if (context.res) {
context.res?.writeHead(302, {
Location: login,
});
context.res?.end();
} else {
Router.replace(login);
}
} else if (WrappedComponent.getInitialProps) {
const wrappedProps = await WrappedComponent.getInitialProps({...context, auth: userAuth});
return { ...wrappedProps, userAuth };
}
return { userAuth };
};
return hocComponent;
};
@deschantkn
Copy link

Works great! although you can't use getServerSideProps or getStaticProps in any page that uses this hoc because getInitialProps is already present

@rubnawazqureshidev
Copy link

@deschantkn, you are right, is there any other solution.

@marcusflat
Copy link

very useful! Thanks

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