Skip to content

Instantly share code, notes, and snippets.

@jgcmarins
Created July 11, 2022 22:37
Show Gist options
  • Save jgcmarins/e01f2ef112f02c1f176c456a6d40cbe9 to your computer and use it in GitHub Desktop.
Save jgcmarins/e01f2ef112f02c1f176c456a6d40cbe9 to your computer and use it in GitHub Desktop.
Next.js SSR authentication and routing between public and private pages with getServerSideProps and cookies
import { GetServerSideProps, GetServerSidePropsContext } from 'next';
import { Me } from '../../types';
import { routes, setCookie } from '../helpers';
import MeQuery from '../graphql/query/MeQuery';
export const getServerSidePropsPrivate: GetServerSideProps<{ me: Me }> = async (
context: GetServerSidePropsContext
) => {
const token = context.req.cookies[process.env.NEXT_COOKIE_NAME];
if (token) {
const data = await MeQuery(token);
if (!data || !data.me) {
context.res.setHeader('Set-Cookie', setCookie.InvalidCookie());
return {
redirect: {
// auth is the root public route
destination: routes.auth,
permanent: false,
},
};
}
return {
props: {
me: data.me,
},
};
}
return {
redirect: {
// auth is the root public route
destination: routes.auth,
permanent: false,
},
};
};
import { GetServerSideProps, GetServerSidePropsContext } from 'next';
import { Me } from '../../types';
import { routes, setCookie } from '../helpers';
import MeQuery from '../graphql/query/MeQuery';
export const getServerSidePropsPublic: GetServerSideProps<{
me: Me | null;
}> = async (context: GetServerSidePropsContext) => {
const token = context.req.cookies[process.env.NEXT_COOKIE_NAME];
if (token) {
const data = await MeQuery(token);
if (data && data.me) {
return {
redirect: {
// app is the root private route
destination: routes.app,
permanent: false,
},
};
} else {
context.res.setHeader('Set-Cookie', setCookie.InvalidCookie());
return {
props: {},
};
}
}
return {
props: {},
};
};
import type { NextPage } from 'next';
import { getServerSidePropsPrivate } from '../../../middlewares/getServerSidePropsPrivate';
const MyPrivatePage: NextPage = ({ me }) => {
// use me data
/* code goes here */
};
export const getServerSideProps = getServerSidePropsPrivate;
export default MyPrivatePage;
import type { NextPage } from 'next';
import { getServerSidePropsPublic } from '../../../middlewares/getServerSidePropsPublic';
const MyPublicPage: NextPage = () => {
/* code goes here */
};
export const getServerSideProps = getServerSidePropsPublic;
export default MyPublicPage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment