npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-linkedin-login-oauth2

v3.0.0

Published

React components for Sign in with LinkedIn using OpenID Connect

Readme

React LinkedIn Login Using OAuth 2.0 and OpenID Connect

All Contributors PRs Welcome

npm package npm

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-oauth2

In 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:

  1. Send the code from the browser to an endpoint on your own backend over HTTPS.
  2. From the backend, send a form-encoded POST request to https://www.linkedin.com/oauth/v2/accessToken.
  3. Include grant_type, code, client_id, client_secret, and the same redirect_uri used for authorization.
  4. Validate the returned ID token before using its claims as an authenticated identity.
  5. Securely store or use the returned access token on the backend.
  6. 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_*, or REACT_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

Props

  • LinkedIn component:

| 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

  • LinkedInCallback component:
    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_liteprofile or r_emailaddress scopes must remain on react-linkedin-login-oauth2@^2 until 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!