Last active
October 5, 2021 15:44
-
-
Save jtomchak/306380bf83c147a50a57faba733c834f to your computer and use it in GitHub Desktop.
Onboarding Check and reroute
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 Head from 'next/head'; | |
import 'styles/globals.css'; | |
import { Nav, RouteGuard } from 'components'; | |
export default App; | |
function App({ Component, pageProps }) { | |
return ( | |
<> | |
<Head> | |
<title>Next.js 11 - Basic HTTP Authentication Example</title> | |
{/* eslint-disable-next-line @next/next/no-css-tags */} | |
<link href="//netdna.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" /> | |
</Head> | |
<div className="app-container bg-light"> | |
<Nav /> | |
<div className="container pt-4 pb-4"> | |
<RouteGuard> | |
<Component {...pageProps} /> | |
</RouteGuard> | |
</div> | |
</div> | |
</> | |
); | |
} |
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 { useState, useEffect } from 'react'; | |
import { useRouter } from 'next/router'; | |
import { userService } from 'services'; | |
export { RouteGuard }; | |
// Rather than authorized / setAuthorized we want to query attendee profile 'onboarding complete' | |
function RouteGuard({ children }) { | |
const router = useRouter(); | |
const [authorized, setAuthorized] = useState(false); | |
useEffect(() => { | |
// on initial load - run auth check | |
authCheck(router.asPath); | |
// on route change start - hide page content by setting authorized to false | |
const hideContent = () => setAuthorized(false); | |
router.events.on('routeChangeStart', hideContent); | |
// on route change complete - run auth check | |
router.events.on('routeChangeComplete', authCheck) | |
// unsubscribe from events in useEffect return function | |
return () => { | |
router.events.off('routeChangeStart', hideContent); | |
router.events.off('routeChangeComplete', authCheck); | |
} | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, []); | |
function authCheck(url) { | |
// redirect to login page if accessing a private page and not logged in | |
const publicPaths = ['/login']; | |
const path = url.split('?')[0]; | |
if (!userService.userValue && !publicPaths.includes(path)) { | |
setAuthorized(false); | |
router.push({ | |
pathname: '/login', | |
query: { returnUrl: router.asPath } | |
}); | |
} else { | |
setAuthorized(true); | |
} | |
} | |
return (authorized && children); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment