DEV Community

Cover image for Next.js and NextAuth.js
Sasidharan
Sasidharan

Posted on

Next.js and NextAuth.js

Passwordless Email login using the link in NextJs - https://lagandlog.com/logs/passwordless-email-login-in-nextjs-using-nextauth

NextAuth.js is a complete open-source authentication solution for Next.js applications.

It has built-in support for all sign-in options out there (such as Google, Github, Twitter, etc)

Supports both JSON Web Tokens and database sessions.

Initialization

Create your NextJs project using,

yarn create next-app
Enter fullscreen mode Exit fullscreen mode

The project will be created and the folder structure will looks like,

.
.
.
\pages
--\api
--\index.jsx
.
\package.json
Enter fullscreen mode Exit fullscreen mode

Install the next-auth dependency using,

yarn add next-auth
Enter fullscreen mode Exit fullscreen mode

Create a folder called auth inside /pages/api

To add NextAuth.js to a project create a file called [...nextauth].js in pages/api/auth.

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

export default NextAuth({
  // Configure one or more authentication providers
  providers: [
    Providers.GitHub({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET
    }),
    // ...add more providers here
  ],

  // A database is optional, but required to persist accounts in a database
  database: process.env.DATABASE_URL,
})
Enter fullscreen mode Exit fullscreen mode

List of other providers

That's it you have integrated Github authentication in your nextjs application.

Default APIs

NextAuth provides various APIs inside the library by default,

You can handle the current session of the user effectively using next-auth/client

// server side
import { getSession } from 'next-auth/client'

// client side hook
import { useSession } from 'next-auth/client'
Enter fullscreen mode Exit fullscreen mode

More about next-auth/client

REST APIs

NextAuth also provides REST APIs out of the box for,

  • GET /api/auth/signin
  • POST /api/auth/signin/:provider
  • GET /api/auth/signout
  • and more

Includes TypeScript support.

yarn add -D @types/next-auth
Enter fullscreen mode Exit fullscreen mode

Works well with and without a database. You can also connect to database ORMs like Prisma.

Prisma ORM Adaptor - view

Learn more at next-auth.js.org

Passwordless Email login using the link in NextJs - https://lagandlog.com/logs/passwordless-email-login-in-nextjs-using-nextauth

That's it. Hopefully, it'll be useful. If you wish, follow me on Twitter.

Top comments (0)