Created
October 23, 2020 18:27
-
-
Save evancloutier/e56231691949e6627b92bc91e6d08ffa to your computer and use it in GitHub Desktop.
Cookie Based Authentication in NextJS Application
This file contains hidden or 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
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(); | |
}, []); | |
} |
This file contains hidden or 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, { 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