├── .env.example ├── .env.production.example ├── .gitignore ├── LICENSE ├── README.md ├── db ├── index.ts ├── schema.prisma └── seed.ts ├── lib ├── auth │ ├── WithAuth.tsx │ ├── passwords.ts │ ├── session.ts │ └── useAuth.ts ├── components │ ├── Layouts │ │ ├── AdminLayout.tsx │ │ └── AppLayout.tsx │ ├── Loader.tsx │ └── NavigationBar.tsx ├── styles │ └── index.css └── types.ts ├── netlify.toml ├── next-env.d.ts ├── next.config.js ├── package.json ├── pages ├── _app.tsx ├── admin │ ├── index.tsx │ ├── setup.tsx │ └── sign-in.tsx ├── api │ ├── auth │ │ ├── [...nextauth].ts │ │ └── administrator │ │ │ └── create.ts │ ├── users.ts │ └── with-session-example.ts ├── client-redirect.tsx ├── client.tsx ├── index.tsx ├── server-redirect.tsx ├── server.tsx ├── sign-in.tsx └── with-session.tsx ├── postcss.config.js ├── public └── assets │ ├── github.svg │ ├── loading.svg │ └── planet-scale.svg ├── tailwind.config.js ├── tsconfig.json └── yarn.lock /.env.example: -------------------------------------------------------------------------------- 1 | DATABASE_URL= 2 | 3 | NEXTAUTH_URL= 4 | NEXTAUTH_SECRET= 5 | 6 | # This is not required, only an example of using NextAuth.js with GitHub as a provider 7 | # See more documentation here: https://next-auth.js.org/providers/github 8 | GITHUB_CLIENT_ID= 9 | GITHUB_CLIENT_SECRET= 10 | -------------------------------------------------------------------------------- /.env.production.example: -------------------------------------------------------------------------------- 1 | DATABASE_URL= 2 | 3 | NEXTAUTH_URL= 4 | NEXTAUTH_SECRET= 5 | 6 | # This is not required, only an example of using NextAuth.js with GitHub as a provider 7 | # See more documentation here: https://next-auth.js.org/providers/github 8 | GITHUB_CLIENT_ID= 9 | GITHUB_CLIENT_SECRET= 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # .env file 4 | .env 5 | 6 | # dependencies 7 | /node_modules 8 | /.pnp 9 | .pnp.js 10 | 11 | # testing 12 | /coverage 13 | 14 | # next.js 15 | /.next/ 16 | /out/ 17 | 18 | # production 19 | /build 20 | 21 | # misc 22 | .DS_Store 23 | *.pem 24 | 25 | # debug 26 | npm-debug.log* 27 | yarn-debug.log* 28 | yarn-error.log* 29 | 30 | # local env files 31 | .env.local 32 | .env.development.local 33 | .env.test.local 34 | .env.production.local 35 | .env.staging 36 | .env.production 37 | 38 | # vercel 39 | .vercel 40 | 41 | # Webstorm 42 | .idea 43 | .vscode 44 | 45 | # Local Netlify folder 46 | .netlify -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 PlanetScale, Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Next.js Starter App for Netlify 2 | 3 | ## Overview 4 | 5 | This README will guide you in getting up and running with Next.js starter app with authentication [NextAuth.js](https://next-auth.js.org/) and deployed on Netlify. Immediately, you can allow users to sign up or login to your app, including a built-in admin panel with a users table (powered by [PlanetScale](https://planetscale.com)). 6 | 7 | We have configured this template for you to one-click deploy directly to Netlify. Alternatively, you can manually deploy to your choice of hosting platform for Next.js applications. For more information on why we created this starter app, read me more in our [blog post](https://planetscale.com/blog/nextjs-netlify-planetscale-starter-app). 8 | 9 | [🖼 Live Demo](https://nextjs-planetscale-starter.netlify.app/) 10 | 11 | ![Example login screen](https://cdn.sanity.io/images/f1avhira/production/9767f106ce5d17f93054ba6ee8a930c546283348-2874x1586.png) 12 | 13 | ## 🥞 Stack 14 | 15 | - Framework - [Next.js v12](https://nextjs.org) 16 | - Language - [TypeScript](https://www.typescriptlang.org/) 17 | - Auth - [NextAuth.js](https://next-auth.js.org/) 18 | - Database - [PlanetScale](https://planetscale.com) 19 | - ORM - [Prisma](https://prisma.io) 20 | - Hosting - [Netlify](https://netlify.com) 21 | - Styling - [TailwindCSS](https://tailwindcss.com) 22 | 23 | ## Getting Started 24 | 25 | To follow along with this guide, you'll need the following: 26 | 27 | - A [free PlanetScale account](https://auth.planetscale.com/sign-up) 28 | - The [PlanetScale CLI](https://github.com/planetscale/cli#installation) 29 | - [Yarn](https://yarnpkg.com/getting-started/install) 30 | - [Node (LTS)](https://nodejs.org/en/) 31 | - A [free Netlify account](https://app.netlify.com/signup) 32 | 33 | ### One-click Deploy with Netlify (recommended) 34 | 35 | The one-click deploy button allows you to connect Netlify to your GitHub account to clone the nextjs-planetscale-starter repository and automatically deploy it. Be sure to sign up for a Netlify account before clicking the deploy button. 36 | 37 | [![Deploy to Netlify button](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/planetscale/nextjs-planetscale-starter) 38 | 39 | Once you click the button, you'll be taken to Netlify’s direct deploy page with the pre-built project’s repository passed as a parameter in the URL. Click the "Connect to GitHub" button to authorize access. 40 | 41 | Next, you'll be asked to configure your site variables. For the Secret value, navigate to [https://generate-secret.now.sh/32](https://generate-secret.now.sh/32) to generate a secret and then paste that in. You can leave the Database URL and NextAuth URL values blank for now. Click "Save & Deploy". 42 | 43 | Your site will take about a minute to build and then you'll be taken to a settings page. A unique Netlify URL will be generated for the project. You can click that now to see your live site! 44 | 45 | **Important:** Once the site is deployed, [follow these steps](https://planetscale.com/docs/tutorials/nextjs-planetscale-netlify-template) to get your PlanetScale database up and running. 46 | 47 | > Note: If you do not follow the steps to get your database set up, you will see a 500 error on your live site. 48 | 49 | ## Admin accounts 50 | 51 | Admin accounts have access to `/admin`, which contains a user dashboard (powered by PlanetScale). This dashboard is a great starting place to build out an admin dashboard for your app. 52 | 53 | ![Example users table](https://cdn.sanity.io/images/f1avhira/production/e2f1b5c5d47887315b2fa17f4039ee9c638e798e-2876x1588.png) 54 | 55 | ## Caveats 56 | 57 | This application is close to production ready, but there are a few things you will need to consider and implement. 58 | 59 | #### What's not in this starter app? 60 | 61 | - **Email Sending & Password Resets:** 62 | We've left this implementation up to the user because we did not want to make adding an email provider a requirement. The default `VerificationToken` schema has the basics required for implementing sign up verification, or password reset requests. 63 | - **API Security:** Although NextAuth.js can be used for authentication, it does not provide authorization out of the box. The application comes with and example of protecting API routes using NextAuth.js. It does not cover things like making sure only administrators can access certain routes or making sure that only a user is able to update their account. 64 | - **Multiple admin accounts** 65 | -------------------------------------------------------------------------------- /db/index.ts: -------------------------------------------------------------------------------- 1 | import { PrismaClient } from "@prisma/client"; 2 | 3 | export * from "@prisma/client"; 4 | 5 | let prisma: PrismaClient; 6 | 7 | if (process.env.NODE_ENV === "production") { 8 | prisma = new PrismaClient({ 9 | errorFormat: "minimal", 10 | }); 11 | } else { 12 | globalThis["prisma"] = 13 | globalThis["prisma"] || 14 | new PrismaClient({ 15 | errorFormat: "pretty", 16 | }); 17 | prisma = globalThis["prisma"]; 18 | } 19 | 20 | export default prisma; 21 | -------------------------------------------------------------------------------- /db/schema.prisma: -------------------------------------------------------------------------------- 1 | // This is your Prisma schema file, 2 | // learn more about it in the docs: https://pris.ly/d/prisma-schema 3 | 4 | datasource db { 5 | provider = "mysql" 6 | url = env("DATABASE_URL") 7 | referentialIntegrity = "prisma" 8 | } 9 | 10 | generator client { 11 | provider = "prisma-client-js" 12 | previewFeatures = ["referentialIntegrity"] 13 | } 14 | 15 | model Account { 16 | id String @id @default(cuid()) 17 | createdAt DateTime @default(now()) 18 | updatedAt DateTime @updatedAt 19 | userId String 20 | type String 21 | provider String 22 | providerAccountId String 23 | refresh_token String? @db.VarChar(500) 24 | access_token String? @db.VarChar(500) 25 | refresh_token_expires_in Int? 26 | expires_at Int? 27 | token_type String? 28 | scope String? 29 | id_token String? @db.Text 30 | session_state String? 31 | oauth_token_secret String? 32 | oauth_token String? 33 | 34 | user User @relation(fields: [userId], references: [id], onDelete: Cascade) 35 | 36 | @@unique([provider, providerAccountId]) 37 | } 38 | 39 | model Session { 40 | id String @id @default(cuid()) 41 | sessionToken String @unique 42 | expires DateTime 43 | user User? @relation(fields: [userId], references: [id], onDelete: Cascade) 44 | userId String? 45 | } 46 | 47 | model User { 48 | id String @id @default(cuid()) 49 | createdAt DateTime @default(now()) 50 | updatedAt DateTime @updatedAt 51 | name String? 52 | email String? @unique 53 | password String? 54 | emailVerified DateTime? 55 | image String? 56 | role String? @default("user") 57 | accounts Account[] 58 | sessions Session[] 59 | } 60 | 61 | model VerificationToken { 62 | identifier String 63 | token String @unique 64 | expires DateTime 65 | 66 | @@unique([identifier, token]) 67 | } 68 | -------------------------------------------------------------------------------- /db/seed.ts: -------------------------------------------------------------------------------- 1 | import { PrismaClient } from "@prisma/client"; 2 | import { hash } from "bcryptjs"; 3 | const prisma = new PrismaClient(); 4 | 5 | async function main() { 6 | const encryptedPassword = await hash("password1234", 12); 7 | await prisma.user.upsert({ 8 | where: { email: "a@a.com" }, 9 | update: {}, 10 | create: { 11 | email: "a@a.com", 12 | name: "Alice", 13 | password: encryptedPassword, 14 | }, 15 | }); 16 | 17 | await prisma.user.upsert({ 18 | where: { email: "b@b.com" }, 19 | update: {}, 20 | create: { 21 | email: "b@b.com", 22 | name: "Bob", 23 | password: encryptedPassword, 24 | }, 25 | }); 26 | 27 | await prisma.user.upsert({ 28 | where: { email: "c@c.com" }, 29 | update: {}, 30 | create: { 31 | email: "c@c.com", 32 | name: "Carla", 33 | password: encryptedPassword, 34 | }, 35 | }); 36 | } 37 | 38 | main() 39 | .catch((e) => { 40 | console.error(e); 41 | process.exit(1); 42 | }) 43 | .finally(async () => { 44 | await prisma.$disconnect(); 45 | }); 46 | -------------------------------------------------------------------------------- /lib/auth/WithAuth.tsx: -------------------------------------------------------------------------------- 1 | import { useSession, signIn } from "next-auth/react"; 2 | import { useEffect } from "react"; 3 | import router from "next/router"; 4 | import Loader from "@lib/components/Loader"; 5 | 6 | function WithAuth({ children, options }) { 7 | const { data: session, status } = useSession(); 8 | const isUser = !!session?.user; 9 | useEffect(() => { 10 | // Do nothing while loading 11 | if (status === "loading") { 12 | return; 13 | } 14 | 15 | // If not authenticated, redirect to provided url or 16 | if (!isUser) { 17 | if (options?.redirectTo) { 18 | router.push(options.redirectTo); 19 | } else { 20 | signIn(); 21 | } 22 | } 23 | }, [isUser, status]); 24 | 25 | if (isUser) { 26 | return children; 27 | } 28 | 29 | // Session is being fetched, or no user. 30 | // If no user, useEffect() will redirect. 31 | return ( 32 |
33 | 34 |
35 | ); 36 | } 37 | 38 | export default WithAuth; 39 | -------------------------------------------------------------------------------- /lib/auth/passwords.ts: -------------------------------------------------------------------------------- 1 | import { hash, compare } from 'bcryptjs'; 2 | 3 | export async function hashPassword(password) { 4 | const hashedPassword = await hash(password, 12); 5 | return hashedPassword; 6 | } 7 | 8 | export async function verifyPassword(password, hashedPassword) { 9 | const isValid = await compare(password, hashedPassword); 10 | return isValid; 11 | } -------------------------------------------------------------------------------- /lib/auth/session.ts: -------------------------------------------------------------------------------- 1 | import { DefaultSession } from "next-auth"; 2 | import { 3 | getSession as getNextSession, 4 | GetSessionParams, 5 | } from "next-auth/react"; 6 | 7 | type DefaultSessionUser = NonNullable; 8 | 9 | type SessionUser = DefaultSessionUser & { 10 | id: string; 11 | role: string; 12 | }; 13 | 14 | export type Session = DefaultSession & { 15 | user?: SessionUser; 16 | }; 17 | 18 | export async function getSession( 19 | options: GetSessionParams 20 | ): Promise { 21 | const session = await getNextSession(options); 22 | 23 | // that these are equal are ensured in `[...nextauth]`'s callback 24 | return session as Session | null; 25 | } 26 | -------------------------------------------------------------------------------- /lib/auth/useAuth.ts: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/planetscale/nextjs-planetscale-starter/4216f41dbd0a6c7374753f794a084d346ed713fe/lib/auth/useAuth.ts -------------------------------------------------------------------------------- /lib/components/Layouts/AdminLayout.tsx: -------------------------------------------------------------------------------- 1 | import { signOut } from "next-auth/react"; 2 | import { Fragment } from "react"; 3 | import { Menu, Transition } from "@headlessui/react"; 4 | import { UserIcon } from "@heroicons/react/outline"; 5 | import { ChevronDownIcon } from "@heroicons/react/solid"; 6 | import classNames from "classnames"; 7 | import Link from "next/link"; 8 | 9 | const navigation = [ 10 | { name: "Users", href: "#", current: true }, 11 | { name: "Help", href: "#", current: false }, 12 | ]; 13 | 14 | const AdminLayout = (props) => { 15 | return ( 16 | <> 17 |
18 |
19 |
20 |
21 |
22 | 33 |
34 |
35 | {/* Profile dropdown */} 36 | 37 |
38 | 39 | 40 | 41 | Open user menu for 42 | {/* {user.name ?? user.email} */} 43 | 44 | 49 |
50 | 59 | 60 | 61 | {({ active }) => ( 62 | signOut()} 64 | className={classNames( 65 | active ? "bg-gray-100" : "", 66 | "block px-4 py-2 text-sm text-gray-700" 67 | )} 68 | > 69 | Logout 70 | 71 | )} 72 | 73 | 74 | 75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 | {navigation.map((item) => ( 83 | 84 | 93 | {item.name} 94 | 95 | 96 | ))} 97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |

110 | {props.title} 111 |

112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 | 120 |
{props.children}
121 |
122 |
123 |
124 | 125 | ); 126 | }; 127 | 128 | export default AdminLayout; 129 | -------------------------------------------------------------------------------- /lib/components/Layouts/AppLayout.tsx: -------------------------------------------------------------------------------- 1 | import classNames from "classnames"; 2 | import { useSession, signOut, signIn } from "next-auth/react"; 3 | import Link from "next/link"; 4 | import { Menu, Transition } from "@headlessui/react"; 5 | import { UserIcon } from "@heroicons/react/outline"; 6 | import { ChevronDownIcon } from "@heroicons/react/solid"; 7 | import { Fragment } from "react"; 8 | import { useRouter } from "next/router"; 9 | 10 | const AppLayout = (props) => { 11 | const { status, data: session } = useSession({ 12 | required: false, 13 | }); 14 | 15 | const router = useRouter(); 16 | 17 | const currentPath = router.pathname; 18 | const NAV_ITEMS = [ 19 | { 20 | title: "Home", 21 | href: "/", 22 | }, 23 | { 24 | title: "Client", 25 | href: "/client", 26 | }, 27 | { 28 | title: "Server", 29 | href: "/server", 30 | }, 31 | { 32 | title: "With Session", 33 | href: "/with-session", 34 | }, 35 | { 36 | title: "Client Redirect", 37 | href: "/client-redirect", 38 | }, 39 | { 40 | title: "Server Redirect", 41 | href: "/server-redirect", 42 | }, 43 | ]; 44 | 45 | return ( 46 | <> 47 |
48 |
49 |
50 |
51 |
52 | 62 |
63 |
64 | 65 |
66 | 67 | {session?.user?.image ? ( 68 | PlanetScale Logo 73 | ) : ( 74 | 75 | )} 76 | 77 | 78 | Open user menu for 79 | 80 | 85 |
86 | 95 | 96 | {status == "authenticated" ? ( 97 | 98 | {({ active }) => ( 99 | signOut()} 101 | className={classNames( 102 | active ? "bg-gray-100" : "", 103 | "block px-4 py-2 text-sm text-gray-700" 104 | )} 105 | > 106 | Sign Out 107 | 108 | )} 109 | 110 | ) : ( 111 | 112 | {({ active }) => ( 113 | signIn()} 115 | className={classNames( 116 | active ? "bg-gray-100" : "", 117 | "block px-4 py-2 text-sm text-gray-700" 118 | )} 119 | > 120 | Sign In 121 | 122 | )} 123 | 124 | )} 125 | 126 | 127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 | {NAV_ITEMS.map((item) => ( 135 | 136 | 147 | {item.title} 148 | 149 | 150 | ))} 151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |

164 | {props.title} 165 |

166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 | 174 |
175 |
176 | {props.children} 177 |
178 |
179 |
180 |
181 |
182 | 183 | ); 184 | }; 185 | 186 | export default AppLayout; 187 | -------------------------------------------------------------------------------- /lib/components/Loader.tsx: -------------------------------------------------------------------------------- 1 | import classNames from "classnames"; 2 | 3 | type LoaderProps = { 4 | className?: string; 5 | absoluteFill?: string; 6 | }; 7 | const Loader = ({ className, absoluteFill }: LoaderProps) => { 8 | return ( 9 |
15 | 19 |
20 | ); 21 | }; 22 | 23 | export default Loader; 24 | -------------------------------------------------------------------------------- /lib/components/NavigationBar.tsx: -------------------------------------------------------------------------------- 1 | /* 2 | This example requires Tailwind CSS v2.0+ 3 | 4 | This example requires some changes to your config: 5 | 6 | ``` 7 | // tailwind.config.js 8 | module.exports = { 9 | // ... 10 | plugins: [ 11 | // ... 12 | require('@tailwindcss/forms'), 13 | ], 14 | } 15 | ``` 16 | */ 17 | import { Fragment } from "react"; 18 | import { Disclosure, Menu, Transition } from "@headlessui/react"; 19 | import { SearchIcon } from "@heroicons/react/solid"; 20 | import { BellIcon, MenuIcon, XIcon } from "@heroicons/react/outline"; 21 | 22 | function classNames(...classes) { 23 | return classes.filter(Boolean).join(" "); 24 | } 25 | 26 | export default function NavigationBar() { 27 | return ( 28 | 29 | {({ open }) => ( 30 | <> 31 |
32 |
33 |
34 |
35 | Workflow 40 |
41 |
42 | {/* Current: "border-indigo-500 text-gray-900", Default: "border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700" */} 43 | 47 | Dashboard 48 | 49 | 53 | Team 54 | 55 | 59 | Projects 60 | 61 | 65 | Calendar 66 | 67 |
68 |
69 |
70 | {/* Mobile menu button */} 71 | 72 | Open main menu 73 | {open ? ( 74 | 79 |
80 |
81 | {/* Profile dropdown */} 82 | 83 |
84 | 85 | Open user menu 86 | 91 | 92 |
93 | 102 | 103 | 104 | {({ active }) => ( 105 | 112 | Your Profile 113 | 114 | )} 115 | 116 | 117 | {({ active }) => ( 118 | 125 | Settings 126 | 127 | )} 128 | 129 | 130 | {({ active }) => ( 131 | 138 | Sign out 139 | 140 | )} 141 | 142 | 143 | 144 |
145 |
146 |
147 |
148 | 149 | 150 |
151 | {/* Current: "bg-indigo-50 border-indigo-500 text-indigo-700", Default: "border-transparent text-gray-600 hover:bg-gray-50 hover:border-gray-300 hover:text-gray-800" */} 152 | 157 | Dashboard 158 | 159 | 164 | Team 165 | 166 | 171 | Projects 172 | 173 | 178 | Calendar 179 | 180 |
181 |
182 |
183 |
184 | 189 |
190 |
191 |
192 | Tom Cook 193 |
194 |
195 | tom@example.com 196 |
197 |
198 | 205 |
206 |
207 | 212 | Your Profile 213 | 214 | 219 | Settings 220 | 221 | 226 | Sign out 227 | 228 |
229 |
230 |
231 | 232 | )} 233 |
234 | ); 235 | } 236 | -------------------------------------------------------------------------------- /lib/styles/index.css: -------------------------------------------------------------------------------- 1 | /* purgecss start ignore */ 2 | @tailwind base; 3 | @tailwind components; 4 | /* purgecss end ignore */ 5 | 6 | @tailwind utilities; 7 | 8 | /* body { 9 | font-family: -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif, 10 | Apple Color Emoji, Segoe UI Emoji; 11 | } */ 12 | 13 | .button { 14 | @apply inline-flex px-2.5 py-1.5 text-xs text-center items-center justify-center border border-transparent font-medium shadow-sm text-white bg-black focus:outline-none focus:ring-1 focus:ring-offset-0 focus:ring-gray-800; 15 | @apply disabled:bg-opacity-80; 16 | @apply rounded-md; 17 | } 18 | 19 | .button__round { 20 | @apply rounded-full !important; 21 | } 22 | 23 | .button__secondary { 24 | @apply bg-white text-black; 25 | @apply border border-gray-400; 26 | } 27 | 28 | .button__third { 29 | @apply bg-black text-white; 30 | } 31 | 32 | .button__sm { 33 | @apply px-2.5 py-1.5 text-xs; 34 | } 35 | 36 | .button__md { 37 | @apply px-3 py-2 text-sm; 38 | } 39 | 40 | .button__lg { 41 | @apply px-4 py-2 text-sm; 42 | } 43 | 44 | .button__xl { 45 | @apply px-6 py-3 text-base; 46 | } 47 | 48 | blockquote { 49 | @apply bg-gray-200; 50 | @apply my-6 p-2; 51 | @apply overflow-auto break-words; 52 | } 53 | 54 | a { 55 | @apply text-blue-300; 56 | } -------------------------------------------------------------------------------- /lib/types.ts: -------------------------------------------------------------------------------- 1 | import { AppProps } from "next/app"; 2 | import { Component } from "react"; 3 | 4 | export type AuthenticatedPage = { 5 | role?: string; 6 | redirectTo?: string; // redirect to this url 7 | }; 8 | export type ExtendedPageProps = { 9 | requiresAuth?: boolean 10 | auth?: AuthenticatedPage; 11 | layout?: Component; 12 | }; 13 | 14 | export type ExtendedAppProps = AppProps & { 15 | Component: ExtendedPageProps; 16 | }; 17 | -------------------------------------------------------------------------------- /netlify.toml: -------------------------------------------------------------------------------- 1 | [build] 2 | command = "yarn db:generate && yarn build" 3 | publish = ".next" 4 | 5 | [[plugins]] 6 | package = "@netlify/plugin-nextjs" 7 | 8 | [template.environment] 9 | NEXTAUTH_SECRET = "Secret, use https://generate-secret.now.sh/32 to create one." 10 | DATABASE_URL = "Database URL, leave blank for now. See docs for more info." 11 | NEXTAUTH_URL = "NextAuth URL, leave blank for now. See docs for more info." 12 | -------------------------------------------------------------------------------- /next-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | /// 4 | 5 | // NOTE: This file should not be edited 6 | // see https://nextjs.org/docs/basic-features/typescript for more information. 7 | -------------------------------------------------------------------------------- /next.config.js: -------------------------------------------------------------------------------- 1 | if (!process.env.NEXTAUTH_URL) { 2 | console.warn( 3 | "\x1b[33mwarn", 4 | "\x1b[0m", 5 | "NEXTAUTH_URL environment variable is not set." 6 | ); 7 | if (process.env.URL) { 8 | process.env.NEXTAUTH_URL = process.env.URL; 9 | console.warn( 10 | "\x1b[33mwarn", 11 | "\x1b[0m", 12 | `NEXTAUTH_URL environment variable is not set. Using Netlify URL ${process.env.URL}.` 13 | ); 14 | } 15 | } 16 | 17 | module.exports = { 18 | target: "experimental-serverless-trace", 19 | future: { 20 | webpack5: true, 21 | }, 22 | typescript: { 23 | ignoreBuildErrors: true, 24 | }, 25 | }; 26 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "starter", 3 | "version": "0.0.0", 4 | "private": true, 5 | "scripts": { 6 | "dev": "next", 7 | "build": "next build", 8 | "start": "next start", 9 | "db:generate": "prisma generate --schema=./db/schema.prisma", 10 | "db:migrate": "prisma migrate dev --schema=./db/schema.prisma --skip-seed", 11 | "db:reset": "prisma migrate reset --schema=./db/schema.prisma --skip-seed", 12 | "db:push": "prisma db push --schema=./db/schema.prisma --skip-seed", 13 | "db:seed": "npx prisma db seed", 14 | "db:studio": "prisma studio --schema=./db/schema.prisma", 15 | "now-build": "yarn generate --schema=./db/schema.prisma && next build" 16 | }, 17 | "dependencies": { 18 | "@headlessui/react": "^1.4.1", 19 | "@heroicons/react": "^1.0.5", 20 | "@next-auth/prisma-adapter": "^0.5.2-next.19", 21 | "@prisma/client": "^3.3.0", 22 | "@tailwindcss/forms": "^0.2.1", 23 | "bcryptjs": "^2.4.3", 24 | "classnames": "^2.3.1", 25 | "lodash": "^4.17.21", 26 | "next": "^12.0.5", 27 | "next-auth": "4.0.0-beta.6", 28 | "next-connect": "^0.10.2", 29 | "react": "^17.0.2", 30 | "react-dom": "^17.0.2", 31 | "react-hook-form": "^7.18.1", 32 | "react-query": "^3.23.2", 33 | "superagent": "^6.1.0" 34 | }, 35 | "prisma": { 36 | "seed": "ts-node --compiler-options {\"module\":\"CommonJS\"} db/seed.ts" 37 | }, 38 | "devDependencies": { 39 | "@netlify/plugin-nextjs": "^4.0.0-beta.4", 40 | "@types/bcryptjs": "^2.4.2", 41 | "@types/lodash": "^4.14.176", 42 | "@types/node": "^14.14.33", 43 | "@types/react": "^17.0.3", 44 | "@types/superagent": "^4.1.13", 45 | "@typescript-eslint/eslint-plugin": "^4.27.0", 46 | "@typescript-eslint/parser": "^4.27.0", 47 | "autoprefixer": "^10.2.5", 48 | "eslint": "^7.29.0", 49 | "eslint-config-prettier": "^8.3.0", 50 | "eslint-plugin-prettier": "^3.4.0", 51 | "eslint-plugin-react": "^7.24.0", 52 | "eslint-plugin-react-hooks": "^4.2.0", 53 | "jest": "^27.0.5", 54 | "lint-staged": "^11.0.0", 55 | "mockdate": "^3.0.5", 56 | "postcss": "^8.2.8", 57 | "prettier": "^2.3.1", 58 | "prisma": "^3.3.0", 59 | "tailwindcss": "^2.2.2", 60 | "ts-node": "^10.4.0", 61 | "typescript": "^4.2.3", 62 | "webpack": "^5.62.1" 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /pages/_app.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import type { ExtendedAppProps } from "@lib/types"; 3 | import { QueryClient, QueryClientProvider } from "react-query"; 4 | import { SessionProvider } from "next-auth/react"; 5 | 6 | import "@lib/styles/index.css"; 7 | import WithAuth from "@lib/auth/WithAuth"; 8 | 9 | export const queryClient = new QueryClient(); 10 | 11 | function MyApp({ 12 | Component, 13 | pageProps: { session, ...pageProps }, 14 | }: ExtendedAppProps) { 15 | return ( 16 | 17 | 18 | {Component.auth ? ( 19 | 20 | 21 | 22 | ) : ( 23 | 24 | )} 25 | 26 | 27 | ); 28 | } 29 | 30 | export default MyApp; 31 | -------------------------------------------------------------------------------- /pages/admin/index.tsx: -------------------------------------------------------------------------------- 1 | import { useQuery } from "react-query"; 2 | import { useSession } from "next-auth/react"; 3 | import { useRouter } from "next/router"; 4 | import { ChevronRightIcon } from "@heroicons/react/solid"; 5 | import { GetServerSidePropsContext } from "next"; 6 | import classNames from "classnames"; 7 | import AdminLayout from "@lib/components/Layouts/AdminLayout"; 8 | import { getSession } from "@lib/auth/session"; 9 | import superagent from "superagent"; 10 | 11 | const statusStyles = { 12 | true: "bg-green-100 text-green-800", 13 | false: "bg-gray-100 text-gray-800", 14 | }; 15 | 16 | function Page() { 17 | const router = useRouter(); 18 | const { 19 | status, 20 | data: { session }, 21 | } = useSession({ 22 | required: true, 23 | onUnauthenticated() { 24 | router.push("/", "/", {}); 25 | }, 26 | }); 27 | 28 | if (status === "loading") { 29 | return "Loading or not authenticated..."; 30 | } 31 | 32 | const usersQuery = useQuery(["users"], async () => { 33 | const data = await superagent.get("/api/users").send({ 34 | select: { 35 | id: true, 36 | name: true, 37 | email: true, 38 | image: true, 39 | emailVerified: true, 40 | accounts: { 41 | select: { 42 | type: true, 43 | provider: true, 44 | }, 45 | }, 46 | }, 47 | }); 48 | 49 | return data.body; 50 | }); 51 | 52 | if (usersQuery.isLoading) { 53 | return
loading...
; 54 | } 55 | 56 | return ( 57 | <> 58 | 59 | {/* {/* Activity list (smallest breakpoint only) */} 60 |
61 | 97 |
98 | 99 | {/* Activity table (small breakpoint and up) */} 100 |
101 |
102 |
103 |
104 | 105 | 106 | 107 | 110 | 113 | 116 | 119 | 120 | 121 | 122 | {usersQuery?.data && 123 | usersQuery.data.map((user) => { 124 | return ( 125 | 126 | 135 | 138 | 152 | 161 | 162 | ); 163 | })} 164 | 165 |
108 | Email 109 | 111 | Name 112 | 114 | Status 115 | 117 | Providers 118 |
127 | 134 | 136 | {user.name} 137 | 139 | 147 | {user.emailVerified 148 | ? "Verified" 149 | : "Not Verified"} 150 | 151 | 153 | {user?.accounts && user?.accounts?.length > 0 ? ( 154 | user.accounts.map((account) => { 155 | return

{account.provider}

; 156 | }) 157 | ) : ( 158 |

credentials

159 | )} 160 |
166 |
167 |
168 |
169 |
170 |
171 | 172 | ); 173 | } 174 | 175 | // Page.auth = true 176 | 177 | export default Page; 178 | 179 | export async function getServerSideProps(context: GetServerSidePropsContext) { 180 | const session = await getSession(context); 181 | 182 | if (!session || session?.user?.role !== "admin") { 183 | return { redirect: { permanent: false, destination: "/" } }; 184 | } 185 | 186 | return { 187 | props: { session: session }, 188 | }; 189 | } 190 | -------------------------------------------------------------------------------- /pages/admin/setup.tsx: -------------------------------------------------------------------------------- 1 | import { getCsrfToken, signIn } from "next-auth/react"; 2 | import { GetServerSidePropsContext } from "next"; 3 | import Head from "next/head"; 4 | import React from "react"; 5 | import { useForm } from "react-hook-form"; 6 | import superagent from "superagent"; 7 | 8 | import prisma from "@db"; 9 | 10 | const MINIMUM_ACTIVITY_TIMEOUT = 850; 11 | type LoginFormValues = { 12 | csrfToken: string; 13 | email: string; 14 | password: string; 15 | }; 16 | 17 | export default function Page({ csrfToken }) { 18 | const [isSubmitting, setSubmitting] = React.useState(false); 19 | 20 | const { register, handleSubmit } = useForm(); 21 | 22 | const createAdminAccountHandler = async (data: LoginFormValues) => { 23 | const response = await superagent 24 | .post("/api/auth/administrator/create") 25 | .send({ 26 | csrfToken: data.csrfToken, 27 | email: data.email, 28 | password: data.password, 29 | }); 30 | 31 | return response.body; 32 | }; 33 | const onSubmit = async (data: LoginFormValues) => { 34 | setSubmitting(true); 35 | try { 36 | createAdminAccountHandler(data) 37 | .then((response) => { 38 | signIn("admin-login", { 39 | callbackUrl: "/admin", 40 | email: data.email, 41 | password: data.password, 42 | }); 43 | }) 44 | .catch((error) => {}); 45 | 46 | setTimeout(() => { 47 | setSubmitting(false); 48 | }, MINIMUM_ACTIVITY_TIMEOUT); 49 | } catch (error) { 50 | console.error(error); 51 | // setError(error) 52 | setSubmitting(false); 53 | } 54 | }; 55 | 56 | return ( 57 |
58 | 59 | Setup 60 | 61 | 62 |
63 | PlanetScale Logo 68 |
69 |
70 |
71 |

Welcome to the PlanetScale Next.js Starter App

72 |

Get started by creating an administrative account to setup.

73 |
74 |
75 |
76 |
77 | 84 |
85 | 91 |
92 | 101 |
102 |
103 | 104 |
105 |
106 | 112 |
113 |
114 | 124 |
125 |
126 | 127 |
128 | 139 |
140 |
141 |
142 |
143 |
144 |
145 | ); 146 | } 147 | 148 | export async function getServerSideProps(context: GetServerSidePropsContext) { 149 | const maybeAdministrator = await prisma.user.findFirst({ 150 | where: { 151 | role: "admin", 152 | }, 153 | }); 154 | 155 | if (maybeAdministrator) { 156 | return { 157 | redirect: { 158 | destination: "/", 159 | permanent: false, 160 | }, 161 | }; 162 | } 163 | return { 164 | props: { csrfToken: await getCsrfToken({ req: context.req }) }, 165 | }; 166 | } 167 | -------------------------------------------------------------------------------- /pages/admin/sign-in.tsx: -------------------------------------------------------------------------------- 1 | import { getCsrfToken, getSession, signIn } from "next-auth/react"; 2 | import { GetServerSidePropsContext } from "next"; 3 | import Head from "next/head"; 4 | import React from "react"; 5 | import { useForm } from "react-hook-form"; 6 | 7 | const MINIMUM_ACTIVITY_TIMEOUT = 850; 8 | type LoginFormValues = { 9 | csrfToken: string; 10 | email: string; 11 | password: string; 12 | }; 13 | 14 | export default function Page({ csrfToken }) { 15 | const [isSubmitting, setSubmitting] = React.useState(false); 16 | 17 | const { register, handleSubmit } = useForm(); 18 | 19 | const onSubmit = async (data: LoginFormValues) => { 20 | setSubmitting(true); 21 | try { 22 | signIn("admin-login", { 23 | callbackUrl: "/admin", 24 | redirect: true, 25 | email: data.email, 26 | password: data.password, 27 | }); 28 | 29 | setTimeout(() => { 30 | setSubmitting(false); 31 | }, MINIMUM_ACTIVITY_TIMEOUT); 32 | } catch (error) { 33 | console.error(error); 34 | // setError(error) 35 | setSubmitting(false); 36 | } 37 | }; 38 | 39 | return ( 40 |
41 | 42 | Admin Sign In 43 | 44 | 45 |
46 | PlanetScale Logo 51 |
52 |
53 |
54 |

Admin Sign In

55 |
56 |
57 |
58 |
59 | 66 |
67 | 73 |
74 | 83 |
84 |
85 | 86 |
87 |
88 | 94 |
95 |
96 | 106 |
107 |
108 | 109 |
110 | 121 |
122 |
123 |
124 |
125 |
126 |
127 | ); 128 | } 129 | export async function getServerSideProps(context: GetServerSidePropsContext) { 130 | const session = await getSession(context); 131 | 132 | if (session) { 133 | return { redirect: { permanent: false, destination: "/" } }; 134 | } 135 | 136 | return { 137 | props: { csrfToken: await getCsrfToken({ req: context.req }) }, 138 | }; 139 | } 140 | -------------------------------------------------------------------------------- /pages/api/auth/[...nextauth].ts: -------------------------------------------------------------------------------- 1 | import NextAuth from "next-auth"; 2 | import CredentialsProvider from "next-auth/providers/credentials"; 3 | import GitHubProvider from "next-auth/providers/github"; 4 | import { PrismaAdapter } from "@next-auth/prisma-adapter"; 5 | 6 | import { verifyPassword, hashPassword } from "@lib/auth/passwords"; 7 | import { Session } from "@lib/auth/session"; 8 | import prisma from "@db/index"; 9 | 10 | export default NextAuth({ 11 | adapter: PrismaAdapter(prisma), 12 | secret: process.env.NEXTAUTH_SECRET, 13 | session: { 14 | jwt: true, 15 | }, 16 | pages: { 17 | signIn: "/sign-in", 18 | // signOut: "/auth/logout", 19 | // error: "/auth/error", // Error code passed in query string as ?error= 20 | }, 21 | providers: [ 22 | GitHubProvider({ 23 | clientId: process.env.GITHUB_CLIENT_ID, 24 | clientSecret: process.env.GITHUB_CLIENT_SECRET, 25 | }), 26 | CredentialsProvider({ 27 | id: "app-login", 28 | name: "App Login", 29 | credentials: { 30 | email: { 31 | label: "Email Address", 32 | type: "email", 33 | placeholder: "john.doe@example.com", 34 | }, 35 | password: { 36 | label: "Password", 37 | type: "password", 38 | placeholder: "Your super secure password", 39 | }, 40 | }, 41 | async authorize(credentials) { 42 | try { 43 | let maybeUser = await prisma.user.findFirst({ 44 | where: { 45 | email: credentials.email, 46 | }, 47 | select: { 48 | id: true, 49 | email: true, 50 | password: true, 51 | name: true, 52 | role: true, 53 | }, 54 | }); 55 | 56 | if (!maybeUser) { 57 | if (!credentials.password || !credentials.email) { 58 | throw new Error("Invalid Credentials"); 59 | } 60 | 61 | maybeUser = await prisma.user.create({ 62 | data: { 63 | email: credentials.email, 64 | password: await hashPassword(credentials.password), 65 | }, 66 | select: { 67 | id: true, 68 | email: true, 69 | password: true, 70 | name: true, 71 | role: true, 72 | }, 73 | }); 74 | } else { 75 | const isValid = await verifyPassword( 76 | credentials.password, 77 | maybeUser.password 78 | ); 79 | 80 | if (!isValid) { 81 | throw new Error("Invalid Credentials"); 82 | } 83 | } 84 | 85 | return { 86 | id: maybeUser.id, 87 | email: maybeUser.email, 88 | name: maybeUser.name, 89 | role: maybeUser.role, 90 | }; 91 | } catch (error) { 92 | console.log(error); 93 | throw error; 94 | } 95 | }, 96 | }), 97 | CredentialsProvider({ 98 | id: "admin-login", 99 | name: "Administrator Login", 100 | credentials: { 101 | email: { 102 | label: "Email Address", 103 | type: "email", 104 | placeholder: "john.doe@example.com", 105 | }, 106 | password: { 107 | label: "Password", 108 | type: "password", 109 | placeholder: "Your super secure password", 110 | }, 111 | }, 112 | async authorize(credentials) { 113 | let maybeUser = await prisma.user.findFirst({ 114 | where: { 115 | email: credentials.email, 116 | }, 117 | select: { 118 | id: true, 119 | email: true, 120 | password: true, 121 | name: true, 122 | role: true, 123 | }, 124 | }); 125 | 126 | if (!maybeUser) { 127 | throw new Error("Unauthorized."); 128 | } 129 | 130 | if (maybeUser?.role !== "admin") { 131 | throw new Error("Unauthorized."); 132 | } 133 | 134 | const isValid = await verifyPassword( 135 | credentials.password, 136 | maybeUser.password 137 | ); 138 | 139 | if (!isValid) { 140 | throw new Error("Invalid Credentials"); 141 | } 142 | 143 | return { 144 | id: maybeUser.id, 145 | email: maybeUser.email, 146 | name: maybeUser.name, 147 | role: maybeUser.role, 148 | }; 149 | }, 150 | }), 151 | ], 152 | callbacks: { 153 | async signIn({ user, account, profile, email, credentials }) { 154 | return true; 155 | }, 156 | async redirect({ url, baseUrl }) { 157 | return url.startsWith(baseUrl) ? url : baseUrl; 158 | }, 159 | async jwt({ token, user, account, profile, isNewUser }) { 160 | if (user) { 161 | token.id = user.id; 162 | token.role = user.role; 163 | } 164 | 165 | return token; 166 | }, 167 | async session({ session, token, user }) { 168 | const sess: Session = { 169 | ...session, 170 | user: { 171 | ...session.user, 172 | id: token.id as string, 173 | role: token.role as string, 174 | }, 175 | }; 176 | 177 | return sess; 178 | }, 179 | }, 180 | }); 181 | -------------------------------------------------------------------------------- /pages/api/auth/administrator/create.ts: -------------------------------------------------------------------------------- 1 | import { NextApiRequest, NextApiResponse } from "next"; 2 | import nc from "next-connect"; 3 | import { hashPassword } from "@lib/auth/passwords"; 4 | import prisma from "@db"; 5 | 6 | const post = async (req: NextApiRequest, res: NextApiResponse) => { 7 | try { 8 | const admin = await prisma.user.create({ 9 | data: { 10 | name: req.body.name, 11 | email: req.body.email, 12 | password: await hashPassword(req.body.password), 13 | role: "admin", 14 | }, 15 | select: { 16 | id: true, 17 | name: true, 18 | email: true, 19 | }, 20 | }); 21 | 22 | return res.status(200).json({ 23 | message: "Admin created.", 24 | data: admin, 25 | }); 26 | } catch (error) { 27 | console.error("[api] auth/administrator/create", error); 28 | return res.status(500).json({ statusCode: 500, message: error.message }); 29 | } 30 | }; 31 | 32 | export default nc().post(post); 33 | -------------------------------------------------------------------------------- /pages/api/users.ts: -------------------------------------------------------------------------------- 1 | import { NextApiRequest, NextApiResponse } from "next"; 2 | import isEmpty from "lodash/isEmpty"; 3 | import nc from "next-connect"; 4 | import prisma, { Prisma } from "@db"; 5 | import { getSession } from "@lib/auth/session"; 6 | 7 | const handler = async (req: NextApiRequest, res: NextApiResponse) => { 8 | const session = await getSession({ req }); 9 | 10 | if (!session) { 11 | return res.status(401).json({ 12 | message: "Unauthorized", 13 | }); 14 | } 15 | 16 | const selectInput = isEmpty(req.body?.select) ? undefined : req.body?.select; 17 | const whereInput = isEmpty(req.body?.where) ? undefined : req.body?.where; 18 | const includeInput = isEmpty(req.body?.include) 19 | ? undefined 20 | : req.body?.include; 21 | const orderByInput = isEmpty(req.body?.orderBy) 22 | ? undefined 23 | : req.body?.orderBy; 24 | const cursorInput = isEmpty(req.body?.cursor) ? undefined : req.body?.cursor; 25 | const takeInput = isEmpty(req.body?.take) ? undefined : req.body?.take; 26 | const skipInput = isEmpty(req.body?.skip) ? undefined : req.body?.skip; 27 | const distinctInput = isEmpty(req.body?.distinct) 28 | ? undefined 29 | : req.body?.distinct; 30 | 31 | const findManyArgs: Prisma.UserFindManyArgs = { 32 | select: selectInput, 33 | where: whereInput, 34 | include: includeInput, 35 | orderBy: orderByInput, 36 | cursor: cursorInput, 37 | take: takeInput, 38 | skip: skipInput, 39 | distinct: distinctInput, 40 | }; 41 | 42 | try { 43 | const users = await prisma.user.findMany(findManyArgs); 44 | 45 | return res.status(200).json(users); 46 | } catch (error) { 47 | console.error("[api] user", error); 48 | return res.status(500).json({ statusCode: 500, message: error.message }); 49 | } 50 | }; 51 | 52 | export default nc().get(handler); 53 | -------------------------------------------------------------------------------- /pages/api/with-session-example.ts: -------------------------------------------------------------------------------- 1 | import { getSession } from "@lib/auth/session"; 2 | 3 | export default async (req, res) => { 4 | const session = await getSession({ req }); 5 | 6 | if (session) { 7 | res.send({ 8 | content: 9 | "This is protected content. You can access this content because you are signed in.", 10 | }); 11 | } else { 12 | res.send({ 13 | error: "You must be sign in to view the protected content on this page.", 14 | }); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /pages/client-redirect.tsx: -------------------------------------------------------------------------------- 1 | import AppLayout from "@lib/components/Layouts/AppLayout"; 2 | import { useSession } from "next-auth/react"; 3 | import { useRouter } from "next/router"; 4 | 5 | const Page = () => { 6 | const router = useRouter(); 7 | const { status, data: session } = useSession({ 8 | required: true, 9 | onUnauthenticated() { 10 | router.push("/", "/", {}); 11 | }, 12 | }); 13 | 14 | if (status === "loading") { 15 | return "Loading or not authenticated..."; 16 | } 17 | 18 | return ( 19 | <> 20 | 21 |
22 |

23 | Hello, {`${session.user.name ?? session.user.email}`} This is a 24 | protected route. You can see it because you're logged in. 25 |

26 |
27 | Client Side Rendering This page uses the useSession() React Hook. The 28 | useSession() React Hook is easy to use and allows pages to render very 29 | quickly. The advantage of this approach is that session state is shared 30 | between pages by using the Provider in _app.js so that navigation 31 | between pages using useSession() is very fast. The disadvantage of 32 | useSession() is that it requires client side JavaScript. 33 |
34 |

This page is protected using the useSession hook.

35 |

Either way works.

36 |

37 | But in this case the session is not available on 38 | the first render. 39 |

40 |
41 |
42 | 43 | ); 44 | }; 45 | 46 | export default Page; 47 | -------------------------------------------------------------------------------- /pages/client.tsx: -------------------------------------------------------------------------------- 1 | import AppLayout from "@lib/components/Layouts/AppLayout"; 2 | import { useSession } from "next-auth/react"; 3 | import Loader from "@lib/components/Loader"; 4 | 5 | const Page = () => { 6 | const { status } = useSession({ 7 | required: false, 8 | }); 9 | 10 | if (status === "loading") { 11 | return ; 12 | } 13 | 14 | return ( 15 | <> 16 | 17 |
18 |

This page uses the useSession() React Hook.

19 | 20 |

21 | The useSession() React Hook is easy to use and allows pages to 22 | render very quickly. 23 |

24 | 25 |

26 | The advantage of this approach is that session state is shared 27 | between pages by using the Provider in _app.js so that navigation 28 | between pages using useSession() is very fast. 29 |

30 | 31 |

32 | The disadvantage of useSession() is that it requires client side 33 | JavaScript. 34 |

35 |

This page is protected using the useSession hook.

36 |

Either way works.

37 |

38 | But in this case the session is not available on 39 | the first render. 40 |

41 |
42 |
43 | 44 | ); 45 | }; 46 | 47 | export default Page; 48 | -------------------------------------------------------------------------------- /pages/index.tsx: -------------------------------------------------------------------------------- 1 | import AppLayout from "@lib/components/Layouts/AppLayout"; 2 | import Image from 'next/image'; 3 | 4 | const Page = () => { 5 | return ( 6 | <> 7 | 8 | {/*
*/} 9 |

Welcome to the PlanetScale Next.js Starter App!

10 |

11 | This is an example site to demonstrate how to use{" "} 12 | NextAuth.js for 13 | authentication with PlanetScale and Prisma. 14 |

15 |
16 |

17 | You can find how to get started{" "} 18 | here. 19 |

20 |
21 | 22 | 23 | ); 24 | }; 25 | 26 | export default Page; 27 | -------------------------------------------------------------------------------- /pages/server-redirect.tsx: -------------------------------------------------------------------------------- 1 | import AppLayout from "@lib/components/Layouts/AppLayout"; 2 | import { useSession } from "next-auth/react"; 3 | 4 | const Page = () => { 5 | const { data: session } = useSession(); 6 | return ( 7 | <> 8 | 9 |
10 |

11 | Hello, {`${session.user.name ?? session.user.email}`} This is a 12 | protected route. You can see it because you're logged in. 13 |

14 |
15 |
16 |

This page is protected using Page.auth = true

17 |

Either way works.

18 |

But in this case the session is available on the first render.

19 |
20 |
21 | 22 | ); 23 | }; 24 | 25 | Page.auth = { 26 | redirectTo: "/", 27 | }; 28 | 29 | export default Page; 30 | -------------------------------------------------------------------------------- /pages/server.tsx: -------------------------------------------------------------------------------- 1 | import AppLayout from "@lib/components/Layouts/AppLayout"; 2 | import { useSession } from "next-auth/react"; 3 | import { getSession } from "@lib/auth/session"; 4 | 5 | const Page = () => { 6 | const { status, data: session } = useSession({ 7 | required: false, 8 | }); 9 | 10 | console.log(status, session); 11 | return ( 12 | <> 13 | 14 |
15 |

16 | This page uses the universal getSession() method in 17 | getServerSideProps(). 18 |

19 | 20 |

21 | Using getSession() in getServerSideProps() is the recommended 22 | approach if you need to support Server Side Rendering with 23 | authentication. 24 |

25 | 26 |

27 | The advantage of Server Side Rendering is this page does not require 28 | client side JavaScript. 29 |

30 | 31 |

32 | The disadvantage of Server Side Rendering is that this page is 33 | slower to render. 34 |

35 | 36 |

This page is protected using the useSession hook.

37 |

Either way works.

38 |

39 | But in this case the session is not available on 40 | the first render. 41 |

42 |
43 |
44 | 45 | ); 46 | }; 47 | 48 | export async function getServerSideProps(context) { 49 | return { 50 | props: { 51 | session: await getSession(context), 52 | }, 53 | }; 54 | } 55 | 56 | export default Page; 57 | -------------------------------------------------------------------------------- /pages/sign-in.tsx: -------------------------------------------------------------------------------- 1 | import { filter } from "lodash"; 2 | import { GetServerSidePropsContext } from "next"; 3 | import { 4 | getSession, 5 | getCsrfToken, 6 | signIn, 7 | getProviders, 8 | } from "next-auth/react"; 9 | import Head from "next/head"; 10 | import React from "react"; 11 | import { useForm } from "react-hook-form"; 12 | 13 | const MINIMUM_ACTIVITY_TIMEOUT = 850; 14 | type LoginFormValues = { 15 | csrfToken: string; 16 | email: string; 17 | password: string; 18 | }; 19 | 20 | export default function Page({ csrfToken, providers }) { 21 | const [isSubmitting, setSubmitting] = React.useState(false); 22 | 23 | const { register, handleSubmit } = useForm(); 24 | 25 | const handleProviderSignIn = (provider) => { 26 | signIn(provider.id); 27 | }; 28 | const onSubmit = async (data: LoginFormValues) => { 29 | setSubmitting(true); 30 | try { 31 | signIn("app-login", { 32 | callbackUrl: "/", 33 | email: data.email, 34 | password: data.password, 35 | }); 36 | 37 | setTimeout(() => { 38 | setSubmitting(false); 39 | }, MINIMUM_ACTIVITY_TIMEOUT); 40 | } catch (error) { 41 | console.error(error); 42 | // setError(error) 43 | setSubmitting(false); 44 | } 45 | }; 46 | 47 | return ( 48 |
49 | 50 | Sign In 51 | 52 | 53 |
54 | 55 | PlanetScale Logo 60 | 61 |
62 |
63 |
64 |

65 | Sign In 66 |

67 |

Sign in with an existing account, or create new account.

68 |
69 |
70 |
71 |
75 | 82 |
83 | 89 |
90 | 99 |
100 |
101 | 102 |
103 |
104 | 110 |
111 |
112 | 122 |
123 |
124 | 125 |
126 | 137 |
138 |
139 |
140 |
141 |
142 |
143 | Or with 144 |
145 |
146 | 147 |
148 | {providers.map((provider) => { 149 | return ( 150 | 162 | ); 163 | })} 164 |
165 |
166 |
167 |
168 |
169 |
170 | ); 171 | } 172 | 173 | export async function getServerSideProps(context: GetServerSidePropsContext) { 174 | const session = await getSession(context); 175 | 176 | if (session) { 177 | return { redirect: { permanent: false, destination: "/" } }; 178 | } 179 | 180 | const csrfToken = await getCsrfToken({ req: context.req }); 181 | const providers = filter(await getProviders(), (provider) => { 182 | return provider.type !== "credentials"; 183 | }); 184 | 185 | return { 186 | props: { csrfToken, providers }, 187 | }; 188 | } 189 | -------------------------------------------------------------------------------- /pages/with-session.tsx: -------------------------------------------------------------------------------- 1 | import AppLayout from "@lib/components/Layouts/AppLayout"; 2 | import { useSession, signIn } from "next-auth/react"; 3 | import { useQuery } from "react-query"; 4 | import superagent from "superagent"; 5 | 6 | const Page = () => { 7 | const { status, data: session } = useSession({ 8 | required: false, 9 | }); 10 | 11 | const withSessionQuery = useQuery( 12 | ["with-session-example", session], 13 | async () => { 14 | console.log(session); 15 | const data = await superagent.get("/api/with-session-example"); 16 | 17 | return data.body.content; 18 | }, 19 | { 20 | // The query will not execute until the session exists 21 | enabled: !!session, 22 | } 23 | ); 24 | 25 | if (status === "loading") { 26 | return "Loading or not authenticated..."; 27 | } 28 | 29 | console.log(withSessionQuery); 30 | if (!session) { 31 | return ( 32 | <> 33 | 34 |
35 |

Access Denied

36 |

37 | 40 | to see a secret message 41 |

42 |
43 |
44 | 45 | ); 46 | } 47 | 48 | return ( 49 | <> 50 | 51 |
52 |

53 | Hello, {`${session.user.name ?? session.user.email}`} You can see 54 | this because you're logged in. 55 |

56 |
57 |

58 | This example shows usage with React Query and protected api 59 | routes. 60 |

61 |
62 | {withSessionQuery?.data &&

{withSessionQuery.data}

} 63 |
64 |
65 | 66 | ); 67 | }; 68 | 69 | export default Page; 70 | -------------------------------------------------------------------------------- /postcss.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: { 3 | tailwindcss: {}, 4 | autoprefixer: {}, 5 | }, 6 | } 7 | -------------------------------------------------------------------------------- /public/assets/github.svg: -------------------------------------------------------------------------------- 1 | GitHub -------------------------------------------------------------------------------- /public/assets/loading.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /public/assets/planet-scale.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /tailwind.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | mode: "jit", 3 | purge: [ 4 | "./pages/**/*.{js,ts,jsx,tsx}", 5 | "./lib/components/**/*.{js,ts,jsx,tsx}", 6 | ], 7 | darkMode: "class", 8 | theme: { 9 | extend: {}, 10 | }, 11 | variants: { 12 | extend: {}, 13 | }, 14 | plugins: [require("@tailwindcss/forms")], 15 | }; 16 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "baseUrl": ".", 6 | "paths": { 7 | "@api/*": ["pages/api/*"], 8 | "@lib/*": ["lib/*"], 9 | "@components/*": ["lib/components/*"], 10 | "@components": ["lib/components/index"], 11 | "@db/*": ["db/*"], 12 | "@db": ["db/index"] 13 | }, 14 | "allowJs": true, 15 | "skipLibCheck": true, 16 | "strict": false, 17 | "forceConsistentCasingInFileNames": true, 18 | "noEmit": true, 19 | "esModuleInterop": true, 20 | "module": "esnext", 21 | "moduleResolution": "node", 22 | "resolveJsonModule": true, 23 | "isolatedModules": true, 24 | "jsx": "preserve", 25 | "incremental": true 26 | }, 27 | "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], 28 | "exclude": ["node_modules"] 29 | } 30 | --------------------------------------------------------------------------------