Skip to content

Instantly share code, notes, and snippets.

@jtomchak
Last active October 5, 2021 15:44
Show Gist options
  • Save jtomchak/306380bf83c147a50a57faba733c834f to your computer and use it in GitHub Desktop.
Save jtomchak/306380bf83c147a50a57faba733c834f to your computer and use it in GitHub Desktop.
Onboarding Check and reroute
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>
</>
);
}
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