@enformik/auth
v0.3.0
Published
Enformik website sign-in: an OIDC authorization code + PKCE client for the browser (zero dependencies).
Maintainers
Readme
@enformik/auth
A browser library for user sign-in on your Enformik website: OIDC authorization code + PKCE, zero dependencies. Your site holds no secret key; sign-in happens on the sign-in page hosted by Enformik, and your site only receives a short-lived session token specific to this application.
Full guide (setup, web users, access rules): https://help.enformik.com/en/rehber/web-sitesi-girisi/
Prerequisites
In the console, open your website's Developer site → Site sign-in tab, enable sign-in, and redeploy the site. Every deployment writes the sign-in details (the auth block) into /_enformik/config.json; the library reads its configuration from there.
Usage
npm install @enformik/authimport { createAuth } from '@enformik/auth';
const auth = await createAuth();
// Complete the sign-in redirect when the page loads (does nothing if there is no redirect).
const done = await auth.handleRedirect();
if (done) history.replaceState(null, '', done.returnTo);
if (!auth.isAuthenticated()) {
await auth.login(); // redirects to the sign-in page
} else {
// The Bearer and workspace headers are added automatically; the token is refreshed when it expires.
const res = await auth.fetch('/data/customer?limit=20');
console.log(auth.getUser(), await res.json());
}
// await auth.logout();API
| Member | Description |
|---|---|
| createAuth(options?) | Reads the configuration and sets up the client; throws a not_configured error if site sign-in is not enabled. |
| config | The loaded site configuration (appUrl, apiUrl, workspaceId, auth...). |
| isAuthenticated() | Whether a valid or refreshable session exists. |
| login(returnTo?) | Redirects to the sign-in page; returnTo is the same-origin path to return to after sign-in (anything else, such as an absolute or // URL, becomes /). Throws storage_unavailable before redirecting if the browser storage cannot be written. |
| register(returnTo?) | Redirects to the account creation page (if "self-registration" is enabled for the site). The person sets their password through the link sent to their email, then signs in with login(). |
| handleRedirect() | Completes the return from sign-in; returns { returnTo } or null. It only acts on redirectPath; on every other page it returns null and leaves the page's own ?error= / ?code= parameters alone. Concurrent calls (for example React StrictMode's double effect) share one exchange. |
| getAccessToken() | Returns the current access token, refreshing it if needed (concurrent calls share a single refresh); null if there is no session. Throws token_exchange_failed if the refresh fails for a transient reason (network, timeout, server error): the session is kept, so catch the error and retry later. |
| fetch(path, init?) | Calls the application's API with the session; refreshes once and retries on a 401. path is relative to apiUrl, or a full URL on the same origin as apiUrl (https:; http: only for localhost). Any other target throws origin_not_allowed and nothing is sent, so the token never leaves your application's API. |
| getUser() | { sub, email?, name? } from the ID token, for display in the UI only. |
| deleteAccount() | Permanently deletes the user's own account (right to erasure, as under GDPR/KVKK) and clears the local session; records the user created are not deleted. Throws an account_delete_failed error on failure. |
| logout() | Clears the session and signs out at the sign-in page. |
Options (AuthOptions): config (an object or a URL; default /_enformik/config.json), redirectPath (default /callback), postLogoutPath (default /), storage ('session' by default, 'local', or your own object with getItem/setItem/removeItem).
redirectPath must be one of your site's registered redirect addresses: /, /callback, /auth/callback, /login/callback.
Errors are thrown as EnformikAuthError; its code is one of:
| Code | When |
|---|---|
| not_configured | Site sign-in is not enabled; the configuration is unreadable or not JSON; fetch is called but the configuration has no apiUrl. |
| state_mismatch | The state on return does not match the sign-in that was started. |
| no_pending_login | On redirectPath, a ?code= arrived but there is no pending sign-in (expired, or another tab). |
| login_rejected | On redirectPath, the provider returned an error. |
| token_exchange_failed | The token endpoint refused, was unreachable or took longer than 15 s. A refresh that fails this way keeps the session. |
| not_authenticated | There is no session, or the provider rejected the refresh token (invalid_grant). |
| account_delete_failed | The account deletion request was refused or failed. |
| origin_not_allowed | fetch was asked to call something other than the API origin (or http: outside localhost); nothing was sent. |
| storage_unavailable | The sign-in state or the session could not be written to browser storage (private mode, blocked site data, quota). |
Upgrading from 0.2: getAccessToken() and fetch() can now throw token_exchange_failed on a transient refresh failure, where they used to sign the user out and return null / throw not_authenticated. Wrap calls that assumed only null and retry or show an offline message; null now means only "no session".
Security notes
- Tokens are kept in
sessionStorageby default (cleared when the tab closes); if you choose'local', any script on your site can read them, so we do not recommend it if you load third-party scripts. - The session token is valid only for this application's API; what a user can see is determined not by your site but by the Record access rules in your application.
