├── .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 | 
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 | [](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 | 
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 |
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 |
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 |
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 |