Last active
September 29, 2022 12:14
-
-
Save jeffersonRibeiro/e7327a5f9b5046323c2ab454423d295c to your computer and use it in GitHub Desktop.
Nextjs HOC to deal with authentication for SSR and CSR pages
This file contains 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'; | |
import getAuthSession from 'services/authSession'; | |
function redirect(res) { | |
if (res) { | |
// SSR | |
res.writeHead(302, { Location: '/' }); | |
res.end(); | |
} else { | |
// Client side | |
Router.push('/'); | |
} | |
} | |
export default (Component, { loggedOnly = false } = {}) => { | |
const withAuthSession = props => { | |
return <Component {...props} />; | |
}; | |
withAuthSession.getInitialProps = async ctx => { | |
let authSession; | |
if (ctx.req) { | |
// SSR | |
authSession = ctx.req.authSession; | |
} else { | |
// Client side | |
const [, response] = await getAuthSession(); | |
authSession = response.data.authSession; | |
} | |
if (loggedOnly && !authSession.profile) { | |
redirect(ctx.res); | |
} | |
let componentProps = {}; | |
if (Component.getInitialProps) { | |
componentProps = await Component.getInitialProps(ctx); | |
} | |
return { authSession, ...componentProps }; | |
}; | |
return withAuthSession; | |
}; |
So, does this work with getServerSideProps
?
where are getAuthSession code ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example