Skip to content

Instantly share code, notes, and snippets.

@jeffersonRibeiro
Last active September 29, 2022 12:14
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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;
};
@jeffersonRibeiro
Copy link
Author

Usage example

import React from 'react';

import withAuthSession from 'components/hoc/withAuthSession';

const Admin = ({ authSession }) => {
  return (
    <div>
      {authSession.profile ? <p>User logged.</p> : <p>User not logged.</p>}
    </div>
  );
};

export default withAuthSession(Admin, { loggedOnly: true });

@pablotdv
Copy link

pablotdv commented Jan 3, 2021

So, does this work with getServerSideProps?

@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