React.js
Handle authentication with Secrecy in a React.js app
Get an authenticated Secrecy client
First initialize the Secrecy library with setup
method. if it hasn't been done yet.
Then, attempt to retrieve an authenticated client, either from the current session or local storage with getSecrecyClient
.
If no client is found, initiates a login process with the login
. Finally, on success the client SecrecyClient
is returned.
If there's an error or the login is not completed, it returns null.
app.ts
import { getSecrecyClient, login, SecrecyClient, setup } from '@secrecy/lib';
import React, { useEffect, useState } from 'react';
export default function App() {
// We recommend storing the client in a global state or context if you need to call the client at different levels of the application.
const [client, setClient] = useState<SecrecyClient | null>(null);
useEffect(() => {
if (client !== null) {
return;
}
// Initialize the Secrecy library
void setup();
// Attempt to retrieve an authenticated client from the current session or local storage
const sessionClient = getSecrecyClient(true);
const localStorageClient = getSecrecyClient(false);
const storedClient = sessionClient ?? localStorageClient;
// If a client is found from the current session or local storage, store it in the state
if (storedClient) {
setClient(storedClient);
return;
}
// If no client is found, initiates a secrecy login process
void login({
appId: env.SECRECY_APP_ID,
redirect: true,
path: window.location.pathname,
scopes: {
email: true,
},
backPath: document.referrer,
})
.then((newClient) => {
// On success, the client is returned, store it in the state
setClient(newClient);
})
.catch((e) => {
console.error(e);
});
}, [client]);
}
Get user from Secrecy client
The method secrecyClient.me
is used for fetching the user's data once the client is initialized to get the user data. It returns a SelfUser
object.
app.ts
import React, { useEffect, useState } from 'react';
export default function App() {
const [user, setUser] = useState<SelfUser | null>(null);
// We recommend storing the client in a global state or context if you need to call the client at different levels of the application.
const [client, setClient] = useState<SecrecyClient | null>(null);
useEffect(() => {
if (me !== null || client === null) {
return;
}
void client
.me()
.then((user) => {
setUser(user);
})
.catch((e) => {
console.error(e);
});
}, [client, me]);
}