Skip to content

Instantly share code, notes, and snippets.

@evancloutier
Created October 23, 2020 18:27
Show Gist options
  • Save evancloutier/e56231691949e6627b92bc91e6d08ffa to your computer and use it in GitHub Desktop.
Save evancloutier/e56231691949e6627b92bc91e6d08ffa to your computer and use it in GitHub Desktop.
Cookie Based Authentication in NextJS Application
const App: NextPage<Props> = ({ prop }) => {
const [{ authenticated, loading }, dispatch] = useReducer(
AuthenticationReducer,
{
authenticated: false,
loading: true,
}
);
useEffect(() => {
async function checkAuthentication() {
try {
const { data } = await apolloClient.query<GetMeQuery>({
query: GET_ME,
});
const token = data?.me?.token;
if (token) {
setToken(token);
dispatch({ type: "authenticate" });
}
} catch (error) {
dispatch({ type: "logout" });
}
}
checkAuthentication();
}, []);
}
import React, { Reducer } from "react";
import { NOOP } from "$constants/common";
export interface AuthenticationState {
authenticated: boolean;
loading: boolean;
}
type AuthenticationActions = "authenticate" | "logout";
interface AuthenticationAction {
type: AuthenticationActions;
}
export type AuthenticationContext = {
authenticated: boolean;
authenticate(): void;
logout(): void;
};
export const AuthenticationContext = React.createContext<AuthenticationContext>(
{
authenticated: false,
authenticate: NOOP,
logout: NOOP,
}
);
export const AuthenticationReducer: Reducer<
AuthenticationState,
AuthenticationAction
> = (state, action: AuthenticationAction) => {
switch (action.type) {
case "authenticate":
return { ...state, authenticated: true, loading: false };
case "logout":
return { ...state, authenticated: false, loading: false };
default:
return { ...state, authenticated: false, loading: true };
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment