MCPcopy Index your code
hub / github.com/okta/okta-react

github.com/okta/okta-react @okta-react-6.11.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release okta-react-6.11.0 ↗ · + Follow
352 symbols 816 edges 204 files 2 documented · 1% 2 cross-repo links updated 10d agookta-react-6.11.0 · 2026-03-16★ 13856 open issues

Browse by type

Functions 316 Types & classes 36
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Okta React SDK

npm version build status

Okta React SDK builds on top of the Okta Auth SDK.

This SDK is a toolkit to build Okta integration with many common "router" packages, such as react-router, reach-router, and others.

Users migrating from version 1.x of this SDK that required react-router should see Migrating from 1.x to learn what changes are necessary.

With the Okta Auth SDK, you can:

  • Login and logout from Okta using the OAuth 2.0 API
  • Retrieve user information
  • Determine authentication status
  • Validate the current user's session

All of these features are supported by this SDK. Additionally, using this SDK, you can:

This SDK does not provide any UI components.

This SDK does not currently support Server Side Rendering (SSR)

This library currently supports:

Release Status

:heavy_check_mark: The current stable major version series is: 6.x

Version Status
6.x :heavy_check_mark: Stable
5.x :heavy_check_mark: Stable
4.x :x: Retired
3.x :x: Retired
2.x :x: Retired
1.x :x: Retired

The latest release can always be found on the [releases page][github-releases].

Getting Started

  • If you do not already have a Developer Edition Account, you can create one at https://developer.okta.com/signup/.
  • An Okta Application, configured for Single-Page App (SPA) mode. This is done from the Okta Developer Console. When following the wizard, use the default properties. They are are designed to work with our sample applications.

Helpful Links

Installation

This library is available through npm.

Install @okta/okta-react

npm install --save @okta/okta-react

Install peer dependencies

npm install --save react
npm install --save react-dom
npm install --save react-router-dom     # see note below
npm install --save @okta/okta-auth-js   # requires at least version 5.3.1

⚠️ NOTE ⚠️

The SecureRoute component packaged in this SDK only works with react-router-dom 5.x. If you're using react-router-dom 6.x, you'll have to write your own SecureRoute component.

See these samples to get started

Usage

okta-react provides the means to connect a React SPA with Okta OIDC information. Most commonly, you will connect to a router library such as react-router.

React-Router components (optional)

okta-react provides a number of pre-built components to connect a react-router-based SPA to Okta OIDC information. You can use these components directly, or use them as a basis for building your own components.

  • SecureRoute - A normal Route except authentication is needed to render the component.

⚠️ NOTE ⚠️

The SecureRoute component packaged in this SDK only works with react-router-dom 5.x. If you're using react-router-dom 6.x, you'll have to write your own SecureRoute component.

See these samples to get started

General components

okta-react provides the necessary tools to build an integration with most common React-based SPA routers.

  • Security - Accepts oktaAuth instance (required) and additional configuration as props. This component acts as a React Context Provider that maintains the latest authState and oktaAuth instance for the downstream consumers. This context can be accessed via the useOktaAuth React Hook, or the withOktaAuth Higher Order Component wrapper from it's descendant component.
  • LoginCallback - A simple component which handles the login callback when the user is redirected back to the application from the Okta login site. <LoginCallback> accepts an optional prop errorComponent that will be used to format the output for any error in handling the callback. This component will be passed an error prop that is an error describing the problem. (see the <OktaError> component for the default rendering)

Users of routers other than react-router can use useOktaAuth to see if authState is not null and authState.isAuthenticated is true. If it is false, you can send them to login via oktaAuth.signInWithRedirect(). See the implementation of <LoginCallback> as an example.

Available Hooks

These hooks can be used in a component that is a descendant of a Security component (<Security> provides the necessary context). Class-based components can gain access to the same information via the withOktaAuth Higher Order Component, which provides oktaAuth and authState as props to the wrapped component.

  • useOktaAuth - gives an object with two properties:
  • oktaAuth - the Okta Auth SDK instance.
  • authState - the AuthState object that shows the current authentication state of the user to your app (initial state is null).

Minimal Example in React Router

Create Routes

This example defines 3 routes:

  • / - Anyone can access the home page
  • /protected - Protected is only visible to authenticated users
  • /login/callback - This is where auth is handled for you after redirection

Note: Make sure you have the /login/callback url (absolute url) added in your Okta App's configuration.

A common mistake is to try and apply an authentication requirement to all pages, THEN add an exception for the login page. This often fails because of how routes are evaluated in most routing packages. To avoid this problem, declare specific routes or branches of routes that require authentication without exceptions.

Creating React Router Routes with class-based components

// src/App.js

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, withRouter } from 'react-router-dom';
import { SecureRoute, Security, LoginCallback } from '@okta/okta-react';
import { OktaAuth, toRelativeUrl } from '@okta/okta-auth-js';
import Home from './Home';
import Protected from './Protected';

class App extends Component {
  constructor(props) {
    super(props);
    this.oktaAuth = new OktaAuth({
      issuer: 'https://{yourOktaDomain}/oauth2/default',
      clientId: '{clientId}',
      redirectUri: window.location.origin + '/login/callback'
    });
    this.restoreOriginalUri = async (_oktaAuth, originalUri) => {
      props.history.replace(toRelativeUrl(originalUri || '/', window.location.origin));
    };
  }

  render() {
    return (
      <Security oktaAuth={this.oktaAuth} restoreOriginalUri={this.restoreOriginalUri} >
        <Route path='/' exact={true} component={Home} />
        <SecureRoute path='/protected' component={Protected} />
        <Route path='/login/callback' component={LoginCallback} />
      </Security>
    );
  }
}

const AppWithRouterAccess = withRouter(App);
export default class extends Component {
  render() {
    return (<Router><AppWithRouterAccess/></Router>);
  }
}

Creating React Router Routes with function-based components

import React from 'react';
import { SecureRoute, Security, LoginCallback } from '@okta/okta-react';
import { OktaAuth, toRelativeUrl } from '@okta/okta-auth-js';
import { BrowserRouter as Router, Route, useHistory } from 'react-router-dom';
import Home from './Home';
import Protected from './Protected';

const oktaAuth = new OktaAuth({
  issuer: 'https://{yourOktaDomain}/oauth2/default',
  clientId: '{clientId}',
  redirectUri: window.location.origin + '/login/callback'
});

const App = () => {
  const history = useHistory();
  const restoreOriginalUri = async (_oktaAuth, originalUri) => {
    history.replace(toRelativeUrl(originalUri || '/', window.location.origin));
  };

  return (
    <Security oktaAuth={oktaAuth} restoreOriginalUri={restoreOriginalUri}>
      <Route path='/' exact={true} component={Home} />
      <SecureRoute path='/protected' component={Protected} />
      <Route path='/login/callback' component={LoginCallback} />
    </Security>
  );
};

const AppWithRouterAccess = () => (
  <Router>
    <App />
  </Router>
);

export default AppWithRouterAccess;

Show Login and Logout Buttons (class-based)

// src/Home.js

import React, { Component } from 'react';
import { withOktaAuth } from '@okta/okta-react';

export default withOktaAuth(class Home extends Component {
  constructor(props) {
    super(props);
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
  }

  async login() {
    this.props.oktaAuth.signInWithRedirect();
  }

  async logout() {
    this.props.oktaAuth.signOut('/');
  }

  render() {
    if (!this.props.authState) return 

Loading...

;
    return this.props.authState.isAuthenticated ?
      <button onClick={this.logout}>Logout</button> :
      <button onClick={this.login}>Login</button>;
  }
});

Show Login and Logout Buttons (function-based)

// src/Home.js

const Home = () => {
  const { oktaAuth, authState } = useOktaAuth();

  const login = async () => oktaAuth.signInWithRedirect();
  const logout = async () => oktaAuth.signOut('/');

  if(!authState) {
    return 

Loading...

;
  }

  if(!authState.isAuthenticated) {
    return (





Not Logged in yet


        <button onClick={login}>Login</button>



    );
  }

  return (





Logged in!


      <button onClick={logout}>Logout</button>



  );
};

export default Home;

Use the Access Token (class-based)

When your users are authenticated, your React application has an access token that was issued by your Okta Authorization server. You can use this token to authenticate requests for resources on your server or API. As a hypothetical example, let's say you have an API that provides messages for a user. You could create a MessageList component that gets the access token and uses it to make an authenticated request to your server.

Here is what the React component could look like for this hypothetical example:

```jsx import fetch from 'isomorphic-fetch'; import React, { Component } from 'react'; import { withOktaAuth } from '@okta/okta-react';

export default withOktaAuth(class MessageList extends Component { constructor(props) { super(props) this.state = { messages: null } }

async componentDidMount() { try { const response = await fetch('http://localhost:{serverPort}/api/messages', { headers: { Authorization: 'Bearer ' + this.props.authState.accessToken.accessToken } }); const data = await response.json(); this.setState({ messages: data.messages }); } catch (err) { // handle error as needed } }

render() { if (!this.state.messages) return

Loading...

; const items = this.state.messages.map(message =>

  • {message}
  • ); return <u

    Extension points exported contracts — how you extend this code

    Core symbols most depended-on inside this repo

    Shape

    Function 231
    Method 85
    Class 32
    Interface 4

    Languages

    TypeScript100%

    Modules by API surface

    test/e2e/page-objects/shared/authenticated-home-page.js15 symbols
    test/e2e/page-objects/okta-oie-signin-page.js12 symbols
    test/e2e/page-objects/test-harness-app/app-page.js9 symbols
    test/e2e/page-objects/router-sample-page.js9 symbols
    test/e2e/page-objects/test-harness-app/sessionToken-signin-page.js8 symbols
    test/e2e/page-objects/test-harness-app/protected-page.js7 symbols
    test/e2e/page-objects/okta-signin-page.js7 symbols
    test/e2e/page-objects/mfa-challenge-page.js7 symbols
    test/e2e/page-objects/direct-auth-login-form.js7 symbols
    generator/gulpfile.js/util.js7 symbols
    test/e2e/page-objects/shared/profile-page.js6 symbols
    test/e2e/page-objects/authenticators-page.js6 symbols

    Used by 2 indexed graphs manifest dependencies, hub-wide

    For agents

    $ claude mcp add okta-react \
      -- python -m otcore.mcp_server <graph>

    ⬇ download graph artifact

    Ask about this repo answers extend the page