Skip to content

Instantly share code, notes, and snippets.

@jeffersonRibeiro
Last active September 29, 2022 12:14
Show Gist options
  • Save jeffersonRibeiro/e7327a5f9b5046323c2ab454423d295c to your computer and use it in GitHub Desktop.
Save jeffersonRibeiro/e7327a5f9b5046323c2ab454423d295c to your computer and use it in GitHub Desktop.
Nextjs HOC to deal with authentication for SSR and CSR pages
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;
};
@Rizki36
Copy link

Rizki36 commented Feb 2, 2022

where are getAuthSession code ?

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