LinkedIn is one of the most popular professional social networks, with over 750 million members worldwide. Allowing users to sign in to your Next.js app using their LinkedIn account can be a great way to streamline the signup process. In this guide, we’ll walk through how to add LinkedIn authentication to a Next.js app using NextAuth.js.
Prerequisites
Before we start, there are a few things we need:
– A Next.js app – you can generate a new one using `npx create-next-app`
– A LinkedIn developer account and app – register at https://www.linkedin.com/developers/
– The NextAuth.js library installed – `npm install next-auth`
– OAuth Credentials from LinkedIn – Client ID & Client Secret
Once you’ve created a LinkedIn app, you’ll need to grab the Client ID and Client Secret from the app dashboard. We’ll need these to allow our Next.js app to interface with the LinkedIn API.
Setting up NextAuth.js
NextAuth.js is a complete open source authentication solution for Next.js applications. It handles all of the tricky authentication stuff like session handling, callbacks, token refresh, etc behind a clean API.
To get started, we first need to initialize NextAuth and configure LinkedIn as an authentication provider. Create a `[…nextauth].js` file under `pages/api/auth`:
“`js
import NextAuth from “next-auth”
import LinkedInProvider from “next-auth/providers/linkedin”
export default NextAuth({
providers: [
LinkedInProvider({
clientId: process.env.LINKEDIN_ID,
clientSecret: process.env.LINKEDIN_SECRET
})
]
})
“`
This sets up NextAuth with our LinkedIn OAuth credentials. We’re reading the API keys from environment variables – make sure to configure these.
Implementing the Sign In Button
With the backend configured, let’s implement a sign in button:
“`jsx
import { signIn } from “next-auth/react”
function SignInButton() {
return (
)
}
“`
The `signIn` function from `next-auth/react` initiates the OAuth flow. We pass the provider name `linkedin` to kick off the LinkedIn login specifically.
When a user clicks this button, they’ll be redirected through the OAuth flow on LinkedIn’s servers. Once authorized, they’ll be returned to our app as an authenticated session.
Accessing the User Session
To access details about the signed in user, we can use the `useSession` React hook provided by NextAuth:
“`jsx
import { useSession } from “next-auth/react”
function Profile() {
const { data: session } = useSession()
if (session) {
return (
{session.user.name}
)
}
return
Loading…
}
“`
This allows us to access the user’s profile data, including their name, image, and email address. We can use this profile data to customize and personalize our app for each user.
API Routes with Session
We may also need to access the user session data from our API routes. NextAuth exposes a common `getSession` method that we can use:
“`js
import { getSession } from “next-auth/react”
export default async function handler(req, res) {
const session = await getSession({ req })
if (session) {
// Signed in
res.send({
content: `Welcome ${session.user.name}!`
})
} else {
// Not signed in
res.send({
error: “You must be signed in to view this content”
})
}
}
“`
Now we can gate access to API routes and data based on the user session.
Additional Provider Options
In addition to basic LinkedIn authentication, there are a few other provider options we can configure:
– **Scopes** – Specify LinkedIn API scopes to request
– **Profile** – Customize which profile fields are returned
– **Authorization** – Configure additional OAuth parameters like state and prompt
For example, to request additional profile fields:
“`js
LinkedInProvider({
// …
profile(profile) {
return {
id: profile.id,
name: profile.displayName,
email: profile.emailAddress,
avatar: profile.profilePicture.displayImage~.elements[3].identifiers[0].identifier
}
}
})
“`
Review the [NextAuth.js LinkedIn configuration docs](https://next-auth.js.org/providers/linkedin) for more details on these options.
Conclusion
Implementing LinkedIn authentication with NextAuth.js provides a straightforward way to add sign in with LinkedIn to a Next.js application. With just a few lines of code, we can offload the entire OAuth flow to NextAuth.js and get back a clean user session.
Some key points:
– Generate OAuth credentials on LinkedIn’s developer platform
– Initialize NextAuth.js with the LinkedIn provider
– Use the `signIn` function to trigger the LinkedIn login flow
– Access the user session anywhere with `useSession` or `getSession`
– Customize profile fields, scopes, authorization options
With these basics implemented, you’ll be ready to enhance your Next.js app with a smooth LinkedIn authentication experience.
Additional Considerations
Here are some additional things to keep in mind when implementing LinkedIn authentication in production:
User Experience
– Provide feedback when loading user session
– Handle errors gracefully – display messages if sign in failed
– Support sign out to destroy the user session
Security
– Use environment variables for secrets/API keys
– Validate user session on server, not just client
– Rotate client secrets periodically
– Consider using JWT callback mode for increased security
Deployment
– Configure CORS and redirects for OAuth callbacks
– Use a reverse proxy or path alias for callback URLs
– Consider deploying callback handling to separate domain
Advanced Integrations
– Request additional LinkedIn APIs like share profile, company pages, etc
– Maintain a mapping of LinkedIn user IDs to your internal user IDs
– Enrich user profiles with LinkedIn data using server hooks
– Build features like “Sign in with LinkedIn” using applied JS SDK
Sample Code
Here is some sample code showing a complete implementation with error handling, loading state, sign out, and protected routes:
“`jsx
// pages/api/auth/[…nextauth].js
import NextAuth from “next-auth”
import LinkedInProvider from “next-auth/providers/linkedin”
export default NextAuth({
providers: [
LinkedInProvider({
clientId: process.env.LINKEDIN_ID,
clientSecret: process.env.LINKEDIN_SECRET
})
]
})
// components/AuthButtons.js
import { signIn, signOut } from “next-auth/react”
export default function AuthButtons() {
return (
)
}
// pages/profile.js
import { useSession, getSession } from “next-auth/react”
import { useRouter } from “next/router”
export default function Profile() {
const router = useRouter()
const { status } = useSession()
if (status === “loading”) {
return
Validating session…
}
if (status === “unauthenticated”) {
router.push(“/login”)
}
// … rest of profile component
}
// pages/api/me.js
import { getSession } from “next-auth/react”
export default async function handler(req, res) {
const session = await getSession({ req })
if (!session) {
res.status(401).json({ error: “Unauthenticated user” })
return
}
res.json({
id: session.user.id,
email: session.user.email
})
}
“`
This shows some best practices like:
– Loading state when checking session
– Redirecting unauthenticated users away from protected routes
– Requiring session on API routes
– Sign out button to destroy session
With these patterns you can build a robust authentication flow in your Next.js app powered by LinkedIn login.
Frequently Asked Questions
Is LinkedIn authentication safe to use?
Yes, LinkedIn authentication is generally very safe to use. As long as you are following best practices like validating sessions on the server and storing secrets properly, the OAuth flow with LinkedIn is secure. Their APIs also use modern security practices like HTTPS and token-based access.
What user profile data does LinkedIn provide?
LinkedIn makes a robust set of profile fields available including name, photo, email, location, job title, and more. You can request additional fields through the LinkedIn API like shared connections, company pages, interests, and skills.
Does LinkedIn authentication work on mobile apps?
Yes, you can enable LinkedIn authentication for mobile apps by using the LinkedIn SDKs for iOS and Android instead of implementing the OAuth flow directly. The SDKs provide a native sign-in experience while still leveraging LinkedIn for authentication.
Do users need a LinkedIn premium account to sign in?
No, a free basic LinkedIn account is sufficient – users do not need a premium subscription. As long as they can authenticate with LinkedIn and agree to share basic profile data, they can sign in to your app.
Can I refresh LinkedIn access tokens to get updated data?
Yes, the access tokens provided by LinkedIn do expire after a period of time. NextAuth.js handles automatically refreshing these tokens in the background so your user sessions remain valid.
Conclusion
Implementing LinkedIn authentication with NextAuth.js is a straightforward way to allow users to sign in with their LinkedIn account. It offloads much of the complexity around sessions, tokens, and OAuth flows. With just a few lines of code, you can get up and running quickly.
And once implemented, there are many additional ways to leverage the LinkedIn platform – sharing content, retrieving company pages, analyzing professional graphs, etc. So it can serve as a foundation for deeper LinkedIn integrations beyond just authentication.