Unverified Commit 6af69793 authored by Balázs Orbán's avatar Balázs Orbán Committed by GitHub

Point to official next-auth example (#22282)

We would like to maintain a single `next-auth` example under our organization. This PR points readers of the Next.js docs to our repository, instead of `with-next-auth`

Also, as @kriscarle pointed out in https://github.com/nextauthjs/next-auth/issues/1132#issuecomment-772375650, we should maybe only maintain a single example to be able to keep it up-to-date more easily.
parent 5032dd92
...@@ -114,16 +114,16 @@ Now that we've discussed authentication patterns, let's look at specific provide ...@@ -114,16 +114,16 @@ Now that we've discussed authentication patterns, let's look at specific provide
<summary><b>Examples</b></summary> <summary><b>Examples</b></summary>
<ul> <ul>
<li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-iron-session">with-iron-session</a></li> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-iron-session">with-iron-session</a></li>
<li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-next-auth">with-next-auth</a></li> <li><a href="https://github.com/nextauthjs/next-auth-example">next-auth-example</a></li>
</ul> </ul>
</details> </details>
If you have an existing database with user data, you'll likely want to utilize an open-source solution that's provider agnostic. If you have an existing database with user data, you'll likely want to utilize an open-source solution that's provider agnostic.
- If you need email/password log-in, use [`next-iron-session`](https://github.com/vercel/next.js/tree/canary/examples/with-iron-session). - If you need email/password log-in, use [`next-iron-session`](https://github.com/vercel/next.js/tree/canary/examples/with-iron-session).
- If you need to persist session data on the server, use [`next-auth`](https://github.com/vercel/next.js/tree/canary/examples/with-next-auth). - If you need to persist session data on the server, use [`next-auth`](https://github.com/nextauthjs/next-auth-example).
- If you need to support social login (Google, Facebook, etc.), use [`next-auth`](https://github.com/vercel/next.js/tree/canary/examples/with-next-auth). - If you need to support social login (Google, Facebook, etc.), use [`next-auth`](https://github.com/nextauthjs/next-auth-example).
- If you want to use [JWTs](https://jwt.io/), use [`next-auth`](https://github.com/vercel/next.js/tree/canary/examples/with-next-auth). - If you want to use [JWTs](https://jwt.io/), use [`next-auth`](https://github.com/nextauthjs/next-auth-example).
Both of these libraries support either authentication pattern. If you're interested in [Passport](http://www.passportjs.org/), we also have examples for it using secure and encrypted cookies: Both of these libraries support either authentication pattern. If you're interested in [Passport](http://www.passportjs.org/), we also have examples for it using secure and encrypted cookies:
......
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_TWITTER_ID=
NEXTAUTH_TWITTER_SECRET=
NEXTAUTH_GITHUB_ID=
NEXTAUTH_GITHUB_SECRET=
NEXTAUTH_GOOGLE_ID=
NEXTAUTH_GOOGLE_SECRET=
NEXTAUTH_FACEBOOK_ID=
NEXTAUTH_FACEBOOK_SECRET=
NEXTAUTH_EMAIL_SERVER=smtp://username:password@smtp.example.com:587
NEXTAUTH_EMAIL_FROM=NextAuth <noreply@example.com>
NEXTAUTH_DATABASE_URL=sqlite://localhost/:memory:?synchronize=true
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
# vercel
.vercel
# NextAuth.js Example # NextAuth.js Example
Next.js example with [`next-auth`](https://github.com/iaincollins/next-auth), an open source, easy to use, and secure by default authentication library. The official example is maintained by the NextAuth.js team. You can find it at this url: https://github.com/nextauthjs/next-auth-example
## How to use
Copy the `.env.local.example` file in this directory to `.env.local` (which will be ignored by Git):
```bash
cp .env.local.example .env.local
```
Then, you'll need to fill at least one of the authentication providers by adding the required secrets for it, be that in the form of OAuth keys/secrets from a provider (Google, Twitter, etc.) or an SMTP connection string to enable email authentication.
More details about the providers can be found [here](https://next-auth.js.org/configuration/providers), and for a more complete introduction to `next-auth` check out their [introduction guide](https://next-auth.js.org/getting-started/introduction)
It is vital that you know the deployment URL and define it in the environment file.
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash
npx create-next-app --example with-next-auth with-next-auth-app
# or
yarn create next-app --example with-next-auth with-next-auth-app
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
**Note:** For production you need to know in advance the domain (deployment URL) of your application, as it would be required for OAuth to work, once you have it set it to the `NEXTAUTH_URL` environment variable under the settings of your Vercel project.
import styles from './footer.module.css'
const Footer = () => (
<div className={styles.footer}>
<hr />
<ul className={styles.navigation}>
<li className={styles.navigationItem}>
<a href="https://github.com/iaincollins/next-auth-example">Source</a>
</li>
<li className={styles.navigationItem}>
<a href="https://next-auth.js.org">Documentation</a>
</li>
</ul>
</div>
)
export default Footer
.footer {
margin-top: 2rem;
}
.navigation {
margin-bottom: 2rem;
padding: 0;
list-style: none;
}
.navigationItem {
display: inline-block;
margin-right: 1rem;
}
import { signin, signout, useSession } from 'next-auth/client'
import styles from './nav.module.css'
/**
* The approach used in this component shows how to built a sign in and sign out
* component that works on pages which support both client and server side
* rendering, and avoids any flash incorrect content on initial page load.
**/
const Nav = () => {
const [session, loading] = useSession()
return (
<nav>
<noscript>
<style>{`.nojs-show { opacity: 1; top: 0; }`}</style>
</noscript>
<p
className={`nojs-show ${
!session && loading ? styles.loading : styles.loaded
}`}
>
{!session && (
<>
<span className={styles.notSignedIn}>Not signed in</span>
<a
href={`/api/auth/signin`}
onClick={(e) => {
e.preventDefault()
signin()
}}
>
<button className={styles.signinButton}>Sign in</button>
</a>
</>
)}
{session && (
<>
<span
style={{ backgroundImage: `url(${session.user.image})` }}
className={styles.avatar}
/>
<span className={styles.signedIn}>
Signed in as <strong>{session.user.email}</strong>
</span>
<a
href={`/api/auth/signout`}
onClick={(e) => {
e.preventDefault()
signout()
}}
>
<button className={styles.signoutButton}>Sign out</button>
</a>
</>
)}
</p>
</nav>
)
}
export default Nav
.loading,
.loaded {
position: relative;
top: 0;
opacity: 1;
overflow: auto;
border-radius: 0 0 0.6rem 0.6rem;
padding: 0.4rem 0.8rem;
margin: 0;
background-color: #f5f5f5;
transition: all 0.2s ease-in-out;
}
.loading {
top: -2rem;
opacity: 0;
}
.signedIn,
.notSignedIn {
position: absolute;
padding: 0.6rem 0 0.4rem 0;
left: 1rem;
right: 7rem;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
display: inherit;
z-index: 1;
}
.signedIn {
left: 3.8rem;
}
.avatar {
border-radius: 2rem;
float: left;
height: 2.2rem;
width: 2.2rem;
background-color: white;
background-size: cover;
border: 2px solid #ddd;
}
.signinButton,
.signoutButton {
float: right;
margin-right: -0.4rem;
font-weight: 500;
background-color: #1eb1fc;
color: #fff;
border: 1px solid #1eb1fc;
border-radius: 2rem;
cursor: pointer;
font-size: 1rem;
line-height: 1rem;
padding: 0.5rem 1rem;
position: relative;
z-index: 10;
}
.signinButton:hover {
background-color: #1b9fe2;
border-color: #1b9fe2;
color: #fff;
}
.signoutButton {
background-color: #fff;
border-color: #bbb;
color: #555;
}
.signoutButton:hover {
background-color: #fff;
border-color: #aaa;
color: #333;
}
{
"name": "with-next-auth",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"license": "MIT",
"dependencies": {
"next": "latest",
"next-auth": "^3.1.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"sqlite3": "^5.0.0"
}
}
import { Provider } from 'next-auth/client'
import '../styles.css'
const App = ({ Component, pageProps }) => {
const { session } = pageProps
return (
<Provider session={session}>
<Component {...pageProps} />
</Provider>
)
}
export default App
import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'
const options = {
// @link https://next-auth.js.org/configuration/providers
providers: [
Providers.Email({
// SMTP connection string or nodemailer configuration object https://nodemailer.com/
server: process.env.NEXTAUTH_EMAIL_SERVER,
// Email services often only allow sending email from a valid/verified address
from: process.env.NEXTAUTH_EMAIL_FROM,
}),
// When configuring oAuth providers make sure you enabling requesting
// permission to get the users email address (required to sign in)
Providers.Google({
clientId: process.env.NEXTAUTH_GOOGLE_ID,
clientSecret: process.env.NEXTAUTH_GOOGLE_SECRET,
}),
Providers.Facebook({
clientId: process.env.NEXTAUTH_FACEBOOK_ID,
clientSecret: process.env.NEXTAUTH_FACEBOOK_SECRET,
}),
Providers.Twitter({
clientId: process.env.NEXTAUTH_TWITTER_ID,
clientSecret: process.env.NEXTAUTH_TWITTER_SECRET,
}),
Providers.GitHub({
clientId: process.env.NEXTAUTH_GITHUB_ID,
clientSecret: process.env.NEXTAUTH_GITHUB_SECRET,
}),
],
// @link https://next-auth.js.org/configuration/databases
database: process.env.NEXTAUTH_DATABASE_URL,
// @link https://next-auth.js.org/configuration/options#session
session: {
// Use JSON Web Tokens for session instead of database sessions.
// This option can be used with or without a database for users/accounts.
// Note: `jwt` is automatically set to `true` if no database is specified.
// jwt: true,
// Seconds - How long until an idle session expires and is no longer valid.
// maxAge: 30 * 24 * 60 * 60, // 30 days
// Seconds - Throttle how frequently to write to database to extend a session.
// Use it to limit write operations. Set to 0 to always update the database.
// Note: This option is ignored if using JSON Web Tokens
// updateAge: 24 * 60 * 60, // 24 hours
},
// @link https://next-auth.js.org/configuration/options#jwt
jwt: {
// A secret to use for key generation - you should set this explicitly
// Defaults to NextAuth.js secret if not explicitly specified.
// secret: 'INp8IvdIyeMcoGAgFGoA61DdBglwwSqnXJZkgz8PSnw',
// Set to true to use encryption. Defaults to false (signing only).
// encryption: true,
// You can define your own encode/decode functions for signing and encryption
// if you want to override the default behaviour.
// encode: async ({ secret, token, maxAge }) => {},
// decode: async ({ secret, token, maxAge }) => {},
},
// @link https://next-auth.js.org/configuration/callbacks
callbacks: {
/**
* Intercept signIn request and return true if the user is allowed.
*
* @link https://next-auth.js.org/configuration/callbacks#sign-in-callback
* @param {object} user User object
* @param {object} account Provider account
* @param {object} profile Provider profile
* @return {boolean} Return `true` (or a modified JWT) to allow sign in
* Return `false` to deny access
*/
signIn: async (user, account, profile) => {
return true
},
/**
* @link https://next-auth.js.org/configuration/callbacks#session-callback
* @param {object} session Session object
* @param {object} user User object (if using database sessions)
* JSON Web Token (if not using database sessions)
* @return {object} Session that will be returned to the client
*/
session: async (session, user) => {
//session.customSessionProperty = 'bar'
return Promise.resolve(session)
},
/**
* @link https://next-auth.js.org/configuration/callbacks#jwt-callback
* @param {object} token Decrypted JSON Web Token
* @param {object} user User object (only available on sign in)
* @param {object} account Provider account (only available on sign in)
* @param {object} profile Provider profile (only available on sign in)
* @param {boolean} isNewUser True if new user (only available on sign in)
* @return {object} JSON Web Token that will be saved
*/
jwt: async (token, user, account, profile, isNewUser) => {
//const isSignIn = (user) ? true : false
// Add auth_time to token on signin in
//if (isSignIn) { token.auth_time = Math.floor(Date.now() / 1000) }
return Promise.resolve(token)
},
},
// You can define custom pages to override the built-in pages
// The routes shown here are the default URLs that will be used.
// @link https://next-auth.js.org/configuration/pages
pages: {
//signIn: '/api/auth/signin',
//signOut: '/api/auth/signout',
//error: '/api/auth/error', // Error code passed in query string as ?error=
//verifyRequest: '/api/auth/verify-request', // (used for check email message)
//newUser: null // If set, new users will be directed here on first sign in
},
// Additional options
// secret: 'abcdef123456789' // Recommended (but auto-generated if not specified)
// debug: true, // Use this option to enable debug messages in the console
}
const Auth = (req, res) => NextAuth(req, res, options)
export default Auth
import Nav from '../components/nav'
import Footer from '../components/footer'
const NextAuth = () => (
<>
<Nav />
<main>
<h1>NextAuth.js Demo</h1>
<p>
This is an example project that uses{' '}
<a href={`https://www.npmjs.com/package/next-auth`}>next-auth</a>.
</p>
<p>
See <a href="https://next-auth.js.org">next-auth.js.org</a> for more
information and documentation. A more full fledged example can be found
at{' '}
<a href="https://next-auth-example.now.sh">next-auth-example.now.sh</a>
</p>
<p>
This live demo uses an in-memory database which is automatically erased
after ~2 hours. More permanent user databases, etc. can be easily
created by defining a db connector your .env file, see{' '}
<a href="https://next-auth.js.org/configuration/database">docs</a>
</p>
</main>
<Footer />
</>
)
export default NextAuth
body {
font-family: 'SF Pro Text', 'SF Pro Icons', 'Helvetica Neue', 'Helvetica',
'Arial', sans-serif;
line-height: 1.4rem;
padding: 0 1rem 1rem 1rem;
max-width: 680px;
margin: 0 auto;
color: #333;
}
h1 {
margin: 0 0 2rem 0;
font-size: 2.5rem;
line-height: 3rem;
font-weight: 300;
}
h4 {
margin-bottom: 0.5rem;
text-transform: uppercase;
}
a {
font-weight: 500;
}
hr {
border: 1px solid #ddd;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment