
Product
Rust Support Now in Beta
Socket's Rust support is moving to Beta: all users can scan Cargo projects and generate SBOMs, including Cargo.toml-only crates, with Rust-aware supply chain checks.
ic-use-internet-identity
Advanced tools
Hook that makes it easy to integrate IC Internet Identity into your React application.
Internet Identity is an authentication service running on the Internet Computer. It allows users to create an identity that can be used to authenticate with canisters (smart contracts) running on the Internet Computer.
ic-use-internet-identity
is a hook that makes it easy to integrate Internet Identity into your React application. It provides a simple interface for logging in and out with the Internet Identity service.
pnpm install ic-use-internet-identity
The hook also requires the following @dfinity/x
packages to be installed with a version of at least 3.1.0
:
pnpm install @dfinity/agent @dfinity/auth-client @dfinity/identity @dfinity/candid
[!TIP] For a complete example, see the ic-use-internet-identity-demo demo project.
To use ic-use-internet-identity
in your React application, follow these steps:
InternetIdentityProvider
componentWrap your application's root component with InternetIdentityProvider
to provide all child components access to the identity context.
// main.tsx
import { InternetIdentityProvider } from "ic-use-internet-identity";
import React from "react";
import ReactDOM from "react-dom/client";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<InternetIdentityProvider>
<App />
</InternetIdentityProvider>
</React.StrictMode>
);
[!TIP] Identity Provider Configuration: The library defaults to using the main Internet Identity instance at
https://identity.ic0.app
. You can override this by setting theidentityProvider
in yourloginOptions
.
- Default:
https://identity.ic0.app
(used automatically)- Custom via loginOptions: Pass
identityProvider
inloginOptions
prop- Local development:
http://${CANISTER_ID_INTERNET_IDENTITY}.localhost:4943
Configure via loginOptions
<InternetIdentityProvider loginOptions={{ identityProvider: process.env.DFX_NETWORK === "local" ? `http://${process.env.CANISTER_ID_INTERNET_IDENTITY}.localhost:4943` : "https://identity.ic0.app" }} > <App /> </InternetIdentityProvider>
login()
function to a buttonThe login()
function initiates the Internet Identity authentication process. Here's what happens when you call it:
status
immediately changes to "logging-in"
and remains there until the process completesstatus
becomes "success"
, identity
is populated, and the popup closesstatus
becomes "error"
and error
contains the error details[!WARNING] User Interaction Required: The
login()
function MUST be called in response to a user interaction (e.g., button click). Calling it inuseEffect
or similar will fail because browsers block popup windows that aren't triggered by user actions.
[!IMPORTANT] No Promise Handling Required: The
login()
function returnsvoid
and handles all results through the hook's state. Monitor thestatus
,error
, andidentity
values returned by the hook instead of using try/catch blocks.
The login process follows a predictable status flow:
"initializing"
→ Library is loading and checking for existing authentication"idle"
→ Ready to login"logging-in"
→ Login popup is open, user is authenticating"success"
→ Login completed successfully, identity
is available"error"
→ Login failed, check error
for detailsUse the status
and error
state variables to track the login process and provide appropriate UI feedback:
// LoginButton.tsx
import { useInternetIdentity } from "ic-use-internet-identity";
export function LoginButton() {
const { login, status, error, isError, identity } = useInternetIdentity();
const renderButton = () => {
switch (status) {
case "initializing":
return (
<button disabled>
⏳ Initializing...
</button>
);
case "idle":
return (
<button onClick={login}>
Login with Internet Identity
</button>
);
case "logging-in":
return (
<button disabled>
🔄 Logging in...
</button>
);
case "success":
return (
<button disabled>
✅ Logged in as {identity?.getPrincipal().toString().slice(0, 8)}...
</button>
);
case "error":
return (
<button onClick={login}>
🔄 Retry Login
</button>
);
default:
return null;
}
};
return (
<div>
{renderButton()}
{isError && (
<div style={{ color: "red", marginTop: "8px" }}>
❌ Login failed: {error?.message}
</div>
)}
</div>
);
}
The hook also provides convenient boolean properties for common status checks:
const {
isInitializing, // status === "initializing"
isIdle, // status === "idle"
isLoggingIn, // status === "logging-in"
isLoginSuccess, // status === "success"
isError // status === "error"
} = useInternetIdentity();
// Example usage
if (isInitializing) {
// Show initial loading state
}
if (isLoggingIn) {
// Show login spinner
}
if (isLoginSuccess && identity) {
// User is authenticated, show protected content
}
identity
context variable to access the identityThe identity
context variable contains the identity of the currently logged in user. The identity is available after successfully loading the identity from local storage or completing the login process.
The preferred way to use the identity is to connect it to the ic-use-actor hook. The hook provides a typed interface to the canister methods as well as interceptor functions for handling errors etc.
// Actors.tsx
import { ReactNode } from "react";
import {
ActorProvider,
createActorContext,
createUseActorHook,
} from "ic-use-actor";
import {
canisterId,
idlFactory,
} from "path-to/your-service/index";
import { _SERVICE } from "path-to/your-service.did";
import { useInternetIdentity } from "ic-use-internet-identity";
const actorContext = createActorContext<_SERVICE>();
export const useActor = createUseActorHook<_SERVICE>(actorContext);
export default function Actors({ children }: { children: ReactNode }) {
const { identity } = useInternetIdentity();
return (
<ActorProvider<_SERVICE>
canisterId={canisterId}
context={actorContext}
identity={identity}
idlFactory={idlFactory}
>
{children}
</ActorProvider>
);
}
{
/** Options for creating the {@link AuthClient}. See AuthClient documentation for list of options
*
*`ic-use-internet-identity` defaults to disabling the AuthClient idle handling (clearing identities
* from store and reloading the window on identity expiry). If that behaviour is preferred, set these settings:
*
* ```
* const options = {
* idleOptions: {
* disableDefaultIdleCallback: false,
* disableIdle: false,
* },
* }
* ```
*/
createOptions?: AuthClientCreateOptions;
/** Options that determine the behaviour of the {@link AuthClient} login call. These options are a subset of
* the {@link AuthClientLoginOptions}. */
loginOptions?: LoginOptions;
/** The child components that the InternetIdentityProvider will wrap. This allows any child
* component to access the authentication context provided by the InternetIdentityProvider. */
children: ReactNode;
}
The LoginOptions
interface extends AuthClientLoginOptions
from @dfinity/auth-client
with some modifications:
import type { AuthClientLoginOptions } from "@dfinity/auth-client";
export interface LoginOptions
extends Omit<
AuthClientLoginOptions,
"onSuccess" | "onError" | "maxTimeToLive"
> {
/**
* Expiration of the authentication in nanoseconds
* @default BigInt(3_600_000_000_000) nanoseconds (1 hour)
*/
maxTimeToLive?: bigint;
}
This means you can use all properties from AuthClientLoginOptions
except onSuccess
, onError
. Available properties include:
identityProvider?: string | URL
- Identity provider URL (defaults to https://identity.ic0.app
)maxTimeToLive?: bigint
- Session expiration (defaults to 1 hour)allowPinAuthentication?: boolean
- Allow PIN/temporary key authenticationderivationOrigin?: string | URL
- Origin for delegated identity generationwindowOpenerFeatures?: string
- Popup window configurationcustomValues?: Record<string, unknown>
- Extra values for login requestexport type Status =
| "initializing"
| "idle"
| "logging-in"
| "success"
| "error";
export type InternetIdentityContext = {
/** The identity is available after successfully loading the identity from local storage
* or completing the login process. */
identity?: Identity;
/** Connect to Internet Identity to login the user. */
login: () => void;
/** Clears the identity from the state and local storage. Effectively "logs the user out". */
clear: () => void;
/** The status of the login process. Note: The login status is not affected when a stored
* identity is loaded on mount. */
status: Status;
/** `status === "initializing"` */
isInitializing: boolean;
/** `status === "idle"` */
isIdle: boolean;
/** `status === "logging-in"` */
isLoggingIn: boolean;
/** `status === "success"` */
isLoginSuccess: boolean;
/** `status === "error"` */
isError: boolean;
/** Login error. Unsurprisingly. */
error?: Error;
};
The library handles all errors through its state management system. You don't need try/catch blocks - simply monitor the error
and isError
state:
import { useInternetIdentity } from "ic-use-internet-identity";
export function LoginComponent() {
const { login, error, isError, status } = useInternetIdentity();
return (
<div>
<button
onClick={login}
disabled={status === "logging-in"}
>
{status === "logging-in" ? "Logging in..." : "Login"}
</button>
{isError && (
<div style={{ color: "red" }}>
Login error: {error?.message}
</div>
)}
</div>
);
}
identity
for changes and handle re-authentication.See the CHANGELOG for details on updates.
Contributions are welcome. Please submit your pull requests or open issues to propose changes or report bugs.
This project is licensed under the MIT License. See the LICENSE file for more details.
[0.4.0] - 2025-08-06
InternetIdentityContextType
→ InternetIdentityContext
(6bad9b7)loginStatus
→ status
loginError
→ error
isLoginError
→ isError
isLoginIdle
→ isIdle
"initializing"
to the Status
type, and isInitializing
is now a computed property (status === "initializing"
) instead of a separate booleanlogin()
now returns void
instead of Promise<void>
clear()
now returns void
instead of Promise<void>
AuthClientLoginOptions
with onSuccess
, onError
omitted (4f04748)https://identity.ic0.app
without requiring environment variable configuration. Custom identity provider can be set via identityProvider
option on the InternetIdentityProvider
. (4f04748)AuthClientLoginOptions
properties are now available (except onSuccess
, onError
)@dfinity/*
packages from >=2.4.1
to >=3.1.0
(828a57c)@xstate/store
from 2.6.2
to ^3.8.5
(e544b5b)setState
action"initializing"
instead of "idle"
with separate initialization flagFAQs
Hook that makes it easy to integrate IC Internet Identity into your React application.
The npm package ic-use-internet-identity receives a total of 251 weekly downloads. As such, ic-use-internet-identity popularity was classified as not popular.
We found that ic-use-internet-identity demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket's Rust support is moving to Beta: all users can scan Cargo projects and generate SBOMs, including Cargo.toml-only crates, with Rust-aware supply chain checks.
Product
Socket Fix 2.0 brings targeted CVE remediation, smarter upgrade planning, and broader ecosystem support to help developers get to zero alerts.
Security News
Socket CEO Feross Aboukhadijeh joins Risky Business Weekly to unpack recent npm phishing attacks, their limited impact, and the risks if attackers get smarter.