react-linkedin-login-oauth2
v3.0.0
Published
React components for Sign in with LinkedIn using OpenID Connect
Maintainers
Readme
React LinkedIn Login Using OAuth 2.0 and OpenID Connect
Demo: https://stupefied-goldberg-b44ee5.netlify.app/
Version 3 uses LinkedIn's current Sign in with LinkedIn using OpenID Connect product. OpenID Connect (OIDC) is an identity layer built on top of OAuth 2.0: OAuth 2.0 provides the authorization-code flow, while OIDC adds the ID token used to authenticate the member. Migrating from version 2? Follow the version 2 to version 3 migration guide.
This library completes the browser portion of LinkedIn's OpenID Connect authorization-code flow and returns an authorization code. It does not exchange that code for tokens. Your application must send the code to its backend, where the backend exchanges it with LinkedIn using the application's client secret. See Exchange the authorization code.
Table of contents
Changelog
See CHANGELOG.md
Installation
Install version 3:
pnpm add react-linkedin-login-oauth2In the LinkedIn Developer Portal, add the Sign in with LinkedIn using OpenID Connect product to your application and register the exact callback URL that you pass as redirectUri.
Overview
Call linkedInLogin using useLinkedIn (recommended) or the LinkedIn render-props component. A popup asks the member to authorize your application. LinkedIn then redirects the popup to your redirectUri, where LinkedInCallback sends the authorization code back to the original window. Your onSuccess callback receives that code.
The authorization code is not an access token or ID token and cannot be used directly to authenticate a user or call LinkedIn APIs. Send it to your backend immediately and exchange it as described below.
Usage
First, we create a button and provide required props:
import { useLinkedIn } from 'react-linkedin-login-oauth2';
// You can use a provided image shipped by this package or your own button.
import linkedin from 'react-linkedin-login-oauth2/assets/linkedin.png';
function LinkedInPage() {
const { linkedInLogin } = useLinkedIn({
clientId: '86vhj2q7ukf83q',
redirectUri: `${window.location.origin}/linkedin`, // for Next.js, you can use `${typeof window === 'object' && window.location.origin}/linkedin`
onSuccess: (code) => {
// Send the authorization code to your own backend.
fetch('/api/auth/linkedin/exchange', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code }),
});
},
onError: (error) => {
console.log(error);
},
popupWidth: 700,
popupHeight: 700,
// Defaults to 'openid profile email'. The library warns if a custom scope omits 'openid'.
});
return (
<img
onClick={linkedInLogin}
src={linkedin}
alt="Sign in with Linked In"
style={{ maxWidth: '180px', cursor: 'pointer' }}
/>
);
}If you do not want to use hooks, the library also provides a render-props component:
import { LinkedIn } from 'react-linkedin-login-oauth2';
// You can use a provided image shipped by this package or your own button.
import linkedin from 'react-linkedin-login-oauth2/assets/linkedin.png';
function LinkedInPage() {
return (
<LinkedIn
clientId="86vhj2q7ukf83q"
redirectUri={`${window.location.origin}/linkedin`}
onSuccess={(code) => {
console.log(code);
}}
onError={(error) => {
console.log(error);
}}
popupWidth={700}
popupHeight={700}
>
{({ linkedInLogin }) => (
<img
onClick={linkedInLogin}
src={linkedin}
alt="Sign in with Linked In"
style={{ maxWidth: '180px', cursor: 'pointer' }}
/>
)}
</LinkedIn>
);
}Render LinkedInCallback at the path configured as your redirectUri. You can use React Router or Next.js routing.
- React Router:
import { LinkedInCallback } from 'react-linkedin-login-oauth2';
import { BrowserRouter, Route, Routes } from 'react-router';
function Demo() {
return (
<BrowserRouter>
<Routes>
<Route path="/linkedin" element={<LinkedInCallback />} />
</Routes>
</BrowserRouter>
);
}- Next.js App Router:
// app/linkedin/page.js
'use client';
import { LinkedInCallback } from 'react-linkedin-login-oauth2';
export default function LinkedInCallbackPage() {
return <LinkedInCallback />;
}Sign-in button image
The existing sign-in image remains bundled for backward compatibility:
import linkedin from 'react-linkedin-login-oauth2/assets/linkedin.png';For current official button images and branding guidance, visit LinkedIn's Sign in with LinkedIn using OpenID Connect documentation and download the assets from its Image Resources section. The additional official image variants are not bundled with this package.
Exchange the authorization code
The code passed to onSuccess is short-lived. Your application should complete these steps immediately:
- Send the code from the browser to an endpoint on your own backend over HTTPS.
- From the backend, send a form-encoded
POSTrequest tohttps://www.linkedin.com/oauth/v2/accessToken. - Include
grant_type,code,client_id,client_secret, and the sameredirect_uriused for authorization. - Validate the returned ID token before using its claims as an authenticated identity.
- Securely store or use the returned access token on the backend.
- Create your application's own login session, preferably using a secure, HTTP-only cookie.
The token exchange must run on a server. For example:
// Server-side code only. Do not include this function in a browser bundle.
async function exchangeLinkedInCode(code) {
const body = new URLSearchParams({
grant_type: 'authorization_code',
code,
client_id: process.env.LINKEDIN_CLIENT_ID,
client_secret: process.env.LINKEDIN_CLIENT_SECRET,
redirect_uri: process.env.LINKEDIN_REDIRECT_URI,
});
const response = await fetch(
'https://www.linkedin.com/oauth/v2/accessToken',
{
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body,
},
);
if (!response.ok) {
throw new Error(`LinkedIn token exchange failed: ${response.status}`);
}
return response.json();
}Your /api/auth/linkedin/exchange handler should call this function with the authorization code received from the browser. Validate the request, handle LinkedIn errors, associate the LinkedIn identity with the correct user, and avoid returning the LinkedIn access token to browser code unless your architecture specifically requires it.
See LinkedIn's official Authorization Code Flow documentation for the request fields, response format, token lifetime, and refresh behavior.
Use the OpenID Connect identity
When openid is requested, LinkedIn's successful token response includes an id_token JWT. Validate it on your backend using LinkedIn's OpenID Connect discovery metadata and JSON Web Key Set. Validate at least the token signature, iss, aud, and exp claims before trusting the identity. Decoding a JWT without verifying it is not authentication.
The verified ID token can contain sub, name, given_name, family_name, picture, email, and email_verified. The email claims are optional and may be absent.
You can also retrieve the member details from LinkedIn's UserInfo endpoint on your backend:
const response = await fetch('https://api.linkedin.com/v2/userinfo', {
headers: { Authorization: `Bearer ${accessToken}` },
});
if (!response.ok) {
throw new Error(`LinkedIn UserInfo request failed: ${response.status}`);
}
const profile = await response.json();See LinkedIn's OpenID Connect documentation for the current claims and endpoints.
Security
[!CAUTION] Never put your LinkedIn Client Secret in frontend source code or expose it to the browser. Do not store it in
VITE_*,NEXT_PUBLIC_*, orREACT_APP_*environment variables, browser storage, query strings, or the published JavaScript bundle. Anyone using the application can inspect those values.
The LinkedIn Client ID is public and may be passed to this library. The Client Secret must remain on your backend, ideally in a server-side environment variable or secret manager. Only your backend should exchange authorization codes for access tokens. Keep the returned access token secure and, where possible, use it from the backend rather than exposing it to the browser.
Demo
- Source code: https://github.com/nvh95/react-linkedin-login-oauth2/blob/master/preview/LinkedInPageHook.jsx
- In action: https://stupefied-goldberg-b44ee5.netlify.app/
Props
LinkedIncomponent:
| Parameter | value | is required | default |
| ----------------- | -------- | :---------: | :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
| clientId | string | yes | |
| redirectUri | string | yes | |
| onSuccess | function | yes | |
| onError | function | no | |
| state | string | no | randomly generated string (recommend to keep default value) |
| scope | string | no | 'openid profile email' |
| | | | Include openid for OIDC. The library warns without blocking if it is omitted. Scope separators using spaces, %20, commas, or + are normalized to spaces. See LinkedIn's OpenID Connect documentation. |
| popupWidth | number | no | 600 |
| popupHeight | number | no | 600 |
| closePopupMessage | string | no | 'User closed the popup' |
| children | function | no | Required when using the LinkedIn component (render props) |
Reference: LinkedIn Authorization Code Flow
LinkedInCallbackcomponent:
No parameters needed
Migration guide
- Upgrading from version 2? See the version 2 to version 3 migration guide.
- Upgrading from version 1? Start with the version 1 to version 2 migration guide, then continue with the version 3 guide.
- Existing applications that still depend on LinkedIn's deprecated
r_liteprofileorr_emailaddressscopes must remain onreact-linkedin-login-oauth2@^2until they migrate their LinkedIn application to OpenID Connect.
Contributors ✨
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!

