├── .gitignore ├── .prettierignore ├── .prettierrc.js ├── .vscode └── settings.json ├── README.md ├── components ├── CustomLink.jsx ├── FullPageLoader.jsx ├── Nav.jsx ├── PrivateRoute.jsx └── UnstyledLink.jsx ├── contexts └── auth.js ├── jsconfig.json ├── next-seo.config.js ├── package.json ├── pages ├── _app.js ├── _document.js ├── blocked-component.jsx ├── blocked-unhandled.jsx ├── blocked.jsx ├── index.jsx └── unprotected.jsx ├── postcss.config.js ├── public └── fonts │ ├── inter-bold-webfont.woff │ ├── inter-bold-webfont.woff2 │ ├── inter-medium-webfont.woff │ ├── inter-medium-webfont.woff2 │ ├── inter-regular-webfont.woff │ └── inter-regular-webfont.woff2 ├── styles └── globals.css ├── tailwind.config.js └── yarn.lock /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # next.js 12 | /.next/ 13 | /out/ 14 | 15 | # production 16 | /build 17 | 18 | # misc 19 | .DS_Store 20 | *.pem 21 | 22 | # debug 23 | npm-debug.log* 24 | yarn-debug.log* 25 | yarn-error.log* 26 | 27 | # local env files 28 | .env.local 29 | .env.development.local 30 | .env.test.local 31 | .env.production.local 32 | 33 | # vercel 34 | .vercel 35 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # next.js 12 | .next 13 | /.next/ 14 | /out/ 15 | 16 | # production 17 | /build 18 | 19 | # misc 20 | .DS_Store 21 | *.pem 22 | 23 | # debug 24 | npm-debug.log* 25 | yarn-debug.log* 26 | yarn-error.log* 27 | 28 | # local env files 29 | .env.local 30 | .env.development.local 31 | .env.test.local 32 | .env.production.local 33 | 34 | # vercel 35 | .vercel 36 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | arrowParens: 'always', 3 | singleQuote: true, 4 | jsxSingleQuote: true, 5 | tabWidth: 4, 6 | overrides: [ 7 | { 8 | files: '*.mdx', 9 | options: { 10 | tabWidth: 2, 11 | }, 12 | }, 13 | ], 14 | }; 15 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "css.validate": false, 3 | "editor.formatOnSave": true 4 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Learn Auth Redirect Nextjs 2 | This is a NextJs and Tailwind project bootstrapped using nextjs-tailwind-starter created by [Theodorus Clarence](https://github.com/theodorusclarence/nextjs-tailwind-starter). 3 | 4 | ## Log 5 | - [x] redirect when is not logged in (works if you directly open /blocked) 6 | - [x] don't show content when waiting to check if logged in (fixed with full page loader) 7 | - [ ] when going to page /blocked using button, still flashes full page loader for a split second 8 | 9 | 10 | 11 | ## Getting Started 12 | 13 | To use this starter, you can use create-next-app to do it by: 14 | ```bash 15 | npx create-next-app -e https://github.com/theodorusclarence/nextjs-tailwind-starter project-name 16 | ``` 17 | 18 | or 19 | 20 | [![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https%3A%2F%2Fgithub.com%2Ftheodorusclarence%2Fnextjs-tailwind-starter) 21 | 22 | First, run the development server: 23 | 24 | ```bash 25 | npm run dev 26 | # or 27 | yarn dev 28 | ``` 29 | 30 | Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. 31 | 32 | You can start editing the page by modifying `pages/index.js`. The page auto-updates as you edit the file 33 | -------------------------------------------------------------------------------- /components/CustomLink.jsx: -------------------------------------------------------------------------------- 1 | import UnstyledLink from './UnstyledLink'; 2 | 3 | export default function CustomLink(props) { 4 | return ( 5 | 9 | {props.children} 10 | 11 | ); 12 | } 13 | -------------------------------------------------------------------------------- /components/FullPageLoader.jsx: -------------------------------------------------------------------------------- 1 | import { ImSpinner5 } from 'react-icons/im'; 2 | 3 | export default function FullPageLoader() { 4 | return ( 5 |
6 | 7 |

Loading...

8 |
9 | ); 10 | } 11 | -------------------------------------------------------------------------------- /components/Nav.jsx: -------------------------------------------------------------------------------- 1 | import Link from 'next/link'; 2 | 3 | const links = [ 4 | { href: '/', label: 'Route' }, 5 | { href: '/', label: 'Route' }, 6 | ]; 7 | 8 | export default function Nav() { 9 | return ( 10 | 28 | ); 29 | } 30 | -------------------------------------------------------------------------------- /components/PrivateRoute.jsx: -------------------------------------------------------------------------------- 1 | import { useEffect } from 'react'; 2 | import { useRouter } from 'next/router'; 3 | 4 | import { useAuth } from '@/contexts/auth'; 5 | import FullPageLoader from './FullPageLoader'; 6 | 7 | export default function PrivateRoute({ protectedRoutes, children }) { 8 | const router = useRouter(); 9 | const { isAuthenticated, isLoading } = useAuth(); 10 | 11 | const pathIsProtected = protectedRoutes.indexOf(router.pathname) !== -1; 12 | 13 | useEffect(() => { 14 | if (!isLoading && !isAuthenticated && pathIsProtected) { 15 | // Redirect route, you can point this to /login 16 | router.push('/'); 17 | } 18 | }, [isLoading, isAuthenticated, pathIsProtected]); 19 | 20 | if ((isLoading || !isAuthenticated) && pathIsProtected) { 21 | return ; 22 | } 23 | 24 | return children; 25 | } 26 | -------------------------------------------------------------------------------- /components/UnstyledLink.jsx: -------------------------------------------------------------------------------- 1 | import Link from 'next/link'; 2 | 3 | export default function UnstyledLink(props) { 4 | const href = props.href; 5 | const isInternalLink = 6 | href && (href.startsWith('/') || href.startsWith('#')); 7 | 8 | if (isInternalLink) { 9 | return ( 10 | 11 | 12 | {props.children} 13 | 14 | 15 | ); 16 | } 17 | 18 | return ( 19 | 25 | {props.children} 26 | 27 | ); 28 | } 29 | -------------------------------------------------------------------------------- /contexts/auth.js: -------------------------------------------------------------------------------- 1 | import React, { createContext, useContext, useState, useEffect } from 'react'; 2 | import { useRouter } from 'next/router'; 3 | const AuthContext = createContext(); 4 | 5 | function AuthProvider({ children }) { 6 | const [user, setUser] = useState({ 7 | error: 'you are logged out, and there is no user object, and no token', 8 | }); 9 | const [isAuthenticated, setIsAuthenticated] = useState(false); 10 | const [isLoading, setIsLoading] = useState(true); 11 | 12 | useEffect(() => { 13 | const token = localStorage.getItem('token'); 14 | console.log('token: ', token); 15 | if (!(token === null || token === undefined)) { 16 | loginWithToken(); 17 | } 18 | setIsLoading(false); 19 | }, []); 20 | 21 | function loginWithToken() { 22 | localStorage.setItem('token', 'true'); 23 | setIsAuthenticated(true); 24 | setUser({ 25 | name: 'hello', 26 | msg: 'Logged in because token in localStorage', 27 | }); 28 | } 29 | function login() { 30 | setIsAuthenticated(true); 31 | setUser({ 32 | name: 'hello', 33 | msg: 'Logged in by clicking login button, you still have no token', 34 | }); 35 | } 36 | 37 | function logout() { 38 | setIsAuthenticated(false); 39 | setUser({ 40 | error: 'you are logged out, and there is no user object, and no token', 41 | }); 42 | localStorage.removeItem('token'); 43 | } 44 | 45 | return ( 46 | 56 | {children} 57 | 58 | ); 59 | } 60 | 61 | const useAuth = () => useContext(AuthContext); 62 | 63 | export { AuthProvider, useAuth }; 64 | -------------------------------------------------------------------------------- /jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleResolution": "node", 3 | "compilerOptions": { 4 | "jsx": "preserve", 5 | "baseUrl": ".", 6 | "paths": { 7 | "@/*": ["*"], 8 | "@/components/*": ["components/*"], 9 | "@/styles/*": ["styles/*"], 10 | }, 11 | }, 12 | "exclude": ["node_modules", ".next"] 13 | } 14 | -------------------------------------------------------------------------------- /next-seo.config.js: -------------------------------------------------------------------------------- 1 | const title = 'Learn Next.js Auth Redirect'; 2 | const description = 3 | 'Attempt to learn how to redirect Next.js protected page without flashing content'; 4 | 5 | const SEO = { 6 | title, 7 | description, 8 | // canonical: 'https://theodorusclarence.com', 9 | openGraph: { 10 | type: 'website', 11 | locale: 'en_IE', 12 | url: 'https://theodorusclarence.com', 13 | title, 14 | description, 15 | images: [ 16 | { 17 | url: 18 | 'https://theodorusclarence.com/favicon/ms-icon-144x144.png', 19 | alt: title, 20 | width: 144, 21 | height: 144, 22 | }, 23 | ], 24 | }, 25 | }; 26 | 27 | export default SEO; 28 | 29 | // EXAMPLES 30 | { 31 | /* 32 | const title = 'Next.js Tailwind Starter'; 33 | const description = 'your description'; 34 | const url = 'https://theodorusclarence.com'; 35 | 36 | ; */ 46 | } 47 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nextjs-tailwind-starter", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "dev": "next dev", 7 | "build": "next build", 8 | "start": "next start" 9 | }, 10 | "dependencies": { 11 | "@tailwindcss/jit": "^0.1.1", 12 | "autoprefixer": "^10.2.1", 13 | "next": "10.0.5", 14 | "next-seo": "^4.17.0", 15 | "postcss": "^8.2.4", 16 | "react": "17.0.1", 17 | "react-dom": "17.0.1", 18 | "react-icons": "^4.2.0", 19 | "tailwindcss": "^2.1.2" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /pages/_app.js: -------------------------------------------------------------------------------- 1 | import { DefaultSeo } from 'next-seo'; 2 | import SEO from '@/next-seo.config'; 3 | import '@/styles/globals.css'; 4 | import { AuthProvider } from '@/contexts/auth'; 5 | import PrivateRoute from '@/components/PrivateRoute'; 6 | 7 | function MyApp({ Component, pageProps }) { 8 | // Add your protected routes here 9 | const protectedRoutes = ['/blocked-component']; 10 | 11 | return ( 12 | <> 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | ); 21 | } 22 | 23 | export default MyApp; 24 | -------------------------------------------------------------------------------- /pages/_document.js: -------------------------------------------------------------------------------- 1 | import Document, { Html, Head, Main, NextScript } from 'next/document'; 2 | 3 | class MyDocument extends Document { 4 | static async getInitialProps(ctx) { 5 | const initialProps = await Document.getInitialProps(ctx); 6 | return { ...initialProps }; 7 | } 8 | 9 | render() { 10 | return ( 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | ); 19 | } 20 | } 21 | 22 | export default MyDocument; 23 | -------------------------------------------------------------------------------- /pages/blocked-component.jsx: -------------------------------------------------------------------------------- 1 | import { useAuth } from '@/contexts/auth'; 2 | 3 | export default function blockedComponent() { 4 | const { user, logout, isAuthenticated } = useAuth(); 5 | 6 | return ( 7 |
8 |

If you can see this, it means you are logged in

9 |

This page did the auth checking on PrivateRoute component.

10 |
{JSON.stringify({ isAuthenticated }, null, 2)}
11 |
{JSON.stringify(user, null, 2)}
12 | 13 |
14 | ); 15 | } 16 | -------------------------------------------------------------------------------- /pages/blocked-unhandled.jsx: -------------------------------------------------------------------------------- 1 | import { useEffect } from 'react'; 2 | import { useRouter } from 'next/router'; 3 | 4 | import { useAuth } from '@/contexts/auth'; 5 | 6 | export default function blocked() { 7 | const router = useRouter(); 8 | 9 | const { isAuthenticated, user, logout, isLoading } = useAuth(); 10 | 11 | useEffect(() => { 12 | if (!isLoading && !isAuthenticated) { 13 | router.push('/'); 14 | } 15 | }, [isLoading, isAuthenticated]); 16 | 17 | return ( 18 |
19 |

20 | If you can see this, it means you are logged in 21 |

22 |

This page did the auth checking directly on the page file.

23 |
{JSON.stringify({ isAuthenticated }, null, 2)}
24 |
{JSON.stringify(user, null, 2)}
25 | 26 |
27 | ); 28 | } 29 | -------------------------------------------------------------------------------- /pages/blocked.jsx: -------------------------------------------------------------------------------- 1 | import { useEffect } from 'react'; 2 | import { useRouter } from 'next/router'; 3 | import { useAuth } from '@/contexts/auth'; 4 | import FullPageLoader from '@/components/FullPageLoader'; 5 | 6 | export default function blocked() { 7 | const router = useRouter(); 8 | 9 | const { isAuthenticated, user, logout, isLoading } = useAuth(); 10 | 11 | useEffect(() => { 12 | if (!isLoading && !isAuthenticated) { 13 | router.push('/'); 14 | } 15 | }, [isAuthenticated, isLoading]); 16 | 17 | if (isLoading || !isAuthenticated) { 18 | return ; 19 | } 20 | 21 | return ( 22 |
23 |

If you can see this, it means you are logged in

24 |

This page did the auth checking directly on the page file.

25 |
{JSON.stringify({ isAuthenticated }, null, 2)}
26 |
{JSON.stringify(user, null, 2)}
27 | 28 |
29 | ); 30 | } 31 | -------------------------------------------------------------------------------- /pages/index.jsx: -------------------------------------------------------------------------------- 1 | import { useEffect, useState } from 'react'; 2 | import { NextSeo } from 'next-seo'; 3 | 4 | import { useAuth } from '@/contexts/auth'; 5 | import CustomLink from '@/components/CustomLink'; 6 | 7 | export default function Home() { 8 | const { user, logout, login, isAuthenticated, loginWithToken } = useAuth(); 9 | const [originLocation, setOriginLocation] = useState( 10 | 'http://localhost:3000' 11 | ); 12 | 13 | useEffect(() => { 14 | if (typeof window !== 'undefined') { 15 | setOriginLocation(window.location.origin); 16 | } 17 | }, []); 18 | 19 | const addToken = () => { 20 | loginWithToken(); 21 | }; 22 | 23 | return ( 24 | <> 25 | 26 | 27 |
28 |
29 |
30 |

Learn Auth Redirect Next.js

31 |

32 | If we open a page and it is not logged in, it will 33 | show a full page loader, then when it is fully 34 | rendered, useEffect will run and push to home page. 35 |

36 |

37 | The blocked-unhandled will show the case when not 38 | using full page loader, and it will flash the 39 | content 40 |

41 | 45 | Check out this blog post for explanation 46 | 47 |
 48 |                             {JSON.stringify({ isAuthenticated }, null, 2)}
 49 |                         
50 |
{JSON.stringify(user, null, 2)}
51 | {isAuthenticated ? ( 52 | 58 | ) : ( 59 | 65 | )} 66 |
67 |

68 | Setting up token, if you add token, then you are 69 | considered logged in even in a new tab 70 |

71 | 74 | 77 |
78 |

79 | List of page (using Next.js Link), will authorized 80 | if login (token & no token): 81 |

82 |
83 | 84 | go to /unprotected page (everyone can access 85 | even if not logged in) 86 | 87 | 88 | go to /blocked-unhandled page (will flash 89 | content, try opening a new tab to see more 90 | clearly) 91 | 92 | 93 | go to /blocked page (won't show content if not 94 | authorized) 95 | 96 | 97 | go to /blocked-component page 98 | 99 |
100 |

101 | Try to directly go to (will open a new tab), will 102 | only authorized if using token: 103 |

104 |
105 | 106 | {originLocation} 107 | /unprotected 108 | 109 | 112 | {originLocation} 113 | /blocked-unhandled 114 | 115 | 116 | {originLocation} 117 | /blocked 118 | 119 | 122 | {originLocation} 123 | /blocked-component 124 | 125 |
126 |
127 |
128 |
129 | 130 | ); 131 | } 132 | -------------------------------------------------------------------------------- /pages/unprotected.jsx: -------------------------------------------------------------------------------- 1 | import CustomLink from '@/components/CustomLink'; 2 | import { useAuth } from '@/contexts/auth'; 3 | 4 | export default function unprotected() { 5 | const { isAuthenticated } = useAuth(); 6 | 7 | return ( 8 |
9 |

10 | This page is unprotected, anyone can see this 11 |

12 |
{JSON.stringify({ isAuthenticated }, null, 2)}
13 | Back To Home 14 |
15 | ); 16 | } 17 | -------------------------------------------------------------------------------- /postcss.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: { 3 | tailwindcss: {}, 4 | autoprefixer: {}, 5 | }, 6 | }; 7 | -------------------------------------------------------------------------------- /public/fonts/inter-bold-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theodorusclarence/learn-auth-redirect-nextjs/d710dadb1404d8557c2d6caf47bf43ec01b51473/public/fonts/inter-bold-webfont.woff -------------------------------------------------------------------------------- /public/fonts/inter-bold-webfont.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theodorusclarence/learn-auth-redirect-nextjs/d710dadb1404d8557c2d6caf47bf43ec01b51473/public/fonts/inter-bold-webfont.woff2 -------------------------------------------------------------------------------- /public/fonts/inter-medium-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theodorusclarence/learn-auth-redirect-nextjs/d710dadb1404d8557c2d6caf47bf43ec01b51473/public/fonts/inter-medium-webfont.woff -------------------------------------------------------------------------------- /public/fonts/inter-medium-webfont.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theodorusclarence/learn-auth-redirect-nextjs/d710dadb1404d8557c2d6caf47bf43ec01b51473/public/fonts/inter-medium-webfont.woff2 -------------------------------------------------------------------------------- /public/fonts/inter-regular-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theodorusclarence/learn-auth-redirect-nextjs/d710dadb1404d8557c2d6caf47bf43ec01b51473/public/fonts/inter-regular-webfont.woff -------------------------------------------------------------------------------- /public/fonts/inter-regular-webfont.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theodorusclarence/learn-auth-redirect-nextjs/d710dadb1404d8557c2d6caf47bf43ec01b51473/public/fonts/inter-regular-webfont.woff2 -------------------------------------------------------------------------------- /styles/globals.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | 5 | @layer base { 6 | /* inter-regular - latin */ 7 | @font-face { 8 | font-family: 'Inter'; 9 | font-style: normal; 10 | font-weight: 400; 11 | font-display: optional; 12 | src: local('Inter'), 13 | url('/fonts/inter-regular-webfont.woff2') format('woff2'), 14 | url('/fonts/inter-regular-webfont.woff') format('woff'); 15 | } 16 | 17 | /* inter-500 - latin */ 18 | @font-face { 19 | font-family: 'Inter'; 20 | font-style: normal; 21 | font-weight: 500; 22 | font-display: optional; 23 | src: local('Inter'), 24 | url('/fonts/inter-medium-webfont.woff2') format('woff2'), 25 | url('/fonts/inter-medium-webfont.woff') format('woff'); 26 | } 27 | 28 | /* inter-700 - latin */ 29 | @font-face { 30 | font-family: 'Inter'; 31 | font-style: normal; 32 | font-weight: 700; 33 | font-display: optional; 34 | src: local('Inter'), 35 | url('/fonts/inter-bold-webfont.woff2') format('woff2'), 36 | url('/fonts/inter-bold-webfont.woff') format('woff'); 37 | } 38 | 39 | /* Write your own custom base styles here */ 40 | h1 { 41 | @apply text-3xl font-bold md:text-5xl font-primary; 42 | } 43 | 44 | h2 { 45 | @apply text-2xl font-bold md:text-4xl font-primary; 46 | } 47 | 48 | h3 { 49 | @apply text-xl font-bold md:text-3xl font-primary; 50 | } 51 | 52 | h4 { 53 | @apply text-lg font-bold font-primary; 54 | } 55 | 56 | body { 57 | @apply text-sm font-primary md:text-base; 58 | } 59 | 60 | .layout { 61 | /* 750px */ 62 | /* max-width: 43.75rem; */ 63 | 64 | /* 1100px */ 65 | max-width: 68.75rem; 66 | @apply w-11/12 mx-auto; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /tailwind.config.js: -------------------------------------------------------------------------------- 1 | const { fontFamily } = require('tailwindcss/defaultTheme'); 2 | 3 | module.exports = { 4 | mode: 'jit', 5 | purge: [ 6 | './pages/**/*.{js,jsx,ts,tsx}', 7 | './components/**/*.{js,jsx,ts,tsx}', 8 | ], 9 | darkMode: false, // or 'media' or 'class' 10 | theme: { 11 | extend: { 12 | fontFamily: { 13 | primary: ['Inter', ...fontFamily.sans], 14 | }, 15 | colors: { 16 | primary: { 17 | 400: '#00E0F3', 18 | 500: '#00c4fd', 19 | }, 20 | }, 21 | }, 22 | }, 23 | variants: { 24 | extend: {}, 25 | }, 26 | plugins: [], 27 | }; 28 | --------------------------------------------------------------------------------