DEV Community

Hein Htoo
Hein Htoo

Posted on

Integrating LinkedIn Authentication with NextAuth.js: A Step-by-Step Guide

I am going to share my experience about integrating linkedin authentication with NextAuth.js.

Previous Post: Implementing auth.js v5 with Prisma and Supabase in Next.js

My GitHub Repo for next-auth Repo

Step 1: Create LinkedIn Application

To allow Next.js application to use LinkedIn as an authentication provider, first create an app inside LinkedIn Developer Portal

It is pretty straight forward but you will need to create LinkedIn Page

LinkedIn App setup

After that go to Auth section and configure your redirect URLs.

Adding redirect URLs

The redirect url should point to Next.js API routes where NextAuth.js handles authentication



http://localhost:3000/api/auth/callback/linkedin


Enter fullscreen mode Exit fullscreen mode

Copy the Client ID and Client Secret for environment variables.

Secrets

Step 2: Adding Environment variables

Create environment variables in .env.local by adding the following environment variables



AUTH_LINKEDIN_ID=your-linkedin-client-id
AUTH_LINKEDIN_SECRET=your-linkedin-client-secret


Enter fullscreen mode Exit fullscreen mode

Step 3: Configure NextAuth.js for LinkedIn

In previous post, we added auth.js like this



// auth.ts
import NextAuth from "next-auth"
import { PrismaAdapter } from "@auth/prisma-adapter"
import { prisma } from "@/prisma"
export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [],
})


Enter fullscreen mode Exit fullscreen mode

Now we are going to add LinkedIn provider



// auth.ts
import NextAuth from "next-auth"
import { PrismaAdapter } from "@auth/prisma-adapter"
import { prisma } from "@/prisma"
import LinkedInProvider from "next-auth/providers/linkedin";

export const { handlers, auth, signIn, signOut } = NextAuth({
  adapter: PrismaAdapter(prisma),
  providers: [
    LinkedInProvider({
      clientId: process.env.AUTH_LINKEDIN_ID ?? "",
      clientSecret: process.env.AUTH_LINKEDIN_SECRET ?? "",
    })
  ],
})


Enter fullscreen mode Exit fullscreen mode

That's all the part of setting up.

Step 4: Login with LinkedIn

You can either login from http://localhost:3000/api/auth/signin or you can create your custom sign-in page.

If you want to customize the sign-in experience, you can create a custom sign-in page.

First, create a file at app/sign-in/page.tsx



import { signIn } from 'next-auth/react'

export default function SignIn() {
  return (
    <div>
      <h1>Sign In</h1>
      <button onClick={() => signIn('linkedin')}>Sign in with LinkedIn</button>
    </div>
  )
}


Enter fullscreen mode Exit fullscreen mode

And that's all for setting up with LinkedIn integration in Auth.js

Happy Coding ^_^

Top comments (0)