Internet Computer Authetication

If you want to integrate Internet Identity into your React project, I recommend using the ic-reactor library. It’s a library I’ve been developing that is designed to simplify authentication and interaction with canisters on the Internet Computer platform. Here’s a quick example to get you started:

Installation

First, install ic-reactor by running:

npm install @ic-reactor/react

Or, if you’re using Yarn:

yarn add @ic-reactor/react

Example Usage

Wrap your App component with the AgentProvider:

import { AgentProvider } from "@ic-reactor/react";
import App from './App';

const Root = () => (
  <AgentProvider withLocalEnv>
    <App />
  </AgentProvider>
);

export default Root;

Use the Login component for handling authentication in your App component:

import { useAuth } from "@ic-reactor/react";

const Login: React.FC = () => {
  const {
    login,
    logout,
    loginLoading,
    loginError,
    identity,
    authenticating,
    authenticated,
  } = useAuth();

  return (
    <>
      <div>
        {loginLoading && <div>Loading...</div>}
        {loginError ? <div>{JSON.stringify(loginError)}</div> : null}
        {identity && <div>{identity.getPrincipal().toText()}</div>}
      </div>
      {authenticated ? (
        <div className="flex flex-col align-center">
          <button onClick={() => logout()}>Logout</button>
        </div>
      ) : (
        <div>
          <button onClick={() => login()} disabled={authenticating}>
            Login
          </button>
        </div>
      )}
    </>
  );
};

export default Login;

For a complete example, you can check out the ic-reactor examples. Additionally, detailed documentation is available here.

Feel free to explore these resources, and if you have any questions, don’t hesitate to reach out!

1 Like