Last active
May 31, 2023 20:10
-
-
Save alieslamifard/dd81ce85e20dc47c57ed6825ff153288 to your computer and use it in GitHub Desktop.
Private route HOC for Next.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works great! although you can't use
getServerSideProps
orgetStaticProps
in any page that uses this hoc becausegetInitialProps
is already present