2023 next-auth-nextjs13開発資料

2023/01/06

How to use next-auth-nextjs13

Next-auth-nextjs13 is a library for adding authentication to Next.js applications. Here is a brief guide on how to use it:

  1. Install the library: npm install next-auth next-auth-client next-auth-redirect next-auth-simple

  2. Add the following code to your pages/api/auth/[...nextauth].js file:

javascript

import NextAuth from 'next-auth'
import Providers from 'next-auth/providers'

const options = {
  providers: [
    Providers.Email({
      server: process.env.EMAIL_SERVER,
      from: process.env.EMAIL_FROM,
    }),
  ],
  secret: process.env.SECRET,
  session: {
    jwt: true,
  },
  jwt: {
    secret: process.env.SECRET,
  },
}

export default (req, res) =NextAuth(req, res, options)
  1. Add the following code to your pages/_app.js file:

javascript

import { useSession } from 'next-auth/client'

function MyApp({ Component, pageProps }) {
  const [session, loading] = useSession()

  return (
    <>
      {loading && <p>Loading authentication status...</p>}
      {!loading && !session && (
        <p>
          <a href="/api/auth/signin">Sign in</a>
        </p>
      )}
      {!loading && session && (
        <p>
          Signed in as {session.user.email}.{' '}
          <a href="/api/auth/signout">Sign out</a>
        </p>
      )}
      <Component {...pageProps} />
    </>
  )
}

export default MyApp
  1. Create a .env file in the root of your project and add the following environment variables:

makefile

SECRET=yoursecret
EMAIL_FROM=you@example.com
EMAIL_SERVER=smtp.example.com
  1. Start your Next.js application: npm run dev

Note: This is a simplified example for demonstration purposes. It is recommended to read the official Next.js documentation and NextAuth documentation to understand the full configuration options and how to use the library in a production environment.

Post Directory