Protect your backend APIs with Node.js SDK
Prerequisites
Prerequisites
Node ≥ 13
Install the SDK
Install the package using npm:
# node 14+ npm install @frontegg/client
Initialize
Frontegg offers multiple components for integration with the Frontegg's scaleable backend and frontend libraries. Initialize the frontegg context when initializing your app.
Regions
Regions
The SDK defaults to Frontegg's EU region, in case you're running on one of the other regions, make sure to change the FRONTEGG_API_GATEWAY_URL
to use your region's URL, instead of api.frontegg.com
.
const { FronteggContext } = require('@frontegg/client'); FronteggContext.init({ FRONTEGG_CLIENT_ID: '<YOUR_CLIENT_ID>', FRONTEGG_API_KEY: '<YOUR_API_KEY>', });
Protect backend routes
Use Frontegg's withAuthentication
auth guard to protect your backend routes. A simple usage example:
const { withAuthentication } = require('@frontegg/client'); // This route can now only be accessed by authenticated users app.use('/protected', withAuthentication(), (req, res) => { // Authenticated user data will be available on the req.frontegg object callSomeAction(req.frontegg.user); res.status(200); });
Use access tokens
When using M2M authentication, access tokens will be cached by the SDK. By default access tokens will be cached locally, however, you can use two other kinds of cache:
- ioredis
- redis
Use Ioredis as your cache
When initializing your context, pass an access tokens options object with your ioredis parameters
const { FronteggContext } = require('@frontegg/client'); const accessTokensOptions = { cache: { type: 'ioredis', options: { host: 'localhost', port: 6379, password: '', db: 10, }, }, }; FronteggContext.init( { FRONTEGG_CLIENT_ID: '<YOUR_CLIENT_ID>', FRONTEGG_API_KEY: '<YOUR_API_KEY>', }, { accessTokensOptions, }, );
Use Redis as your cache
When initializing your context, pass an access tokens options object with your redis parameters:
const { FronteggContext } = require('@frontegg/client'); const accessTokensOptions = { cache: { type: 'redis', options: { url: 'redis[s]://[[username][:password]@][host][:port][/db-number]', }, }, }; FronteggContext.init( { FRONTEGG_CLIENT_ID: '<YOUR_CLIENT_ID>', FRONTEGG_API_KEY: '<YOUR_API_KEY>', }, { accessTokensOptions, }, );
Frontegg clients
Frontegg provides various clients for seamless integration with the Frontegg APIs. The Entitlements client can be used to determine whether an authorized user or tenant is entitled for particular feature or permission. This client is discussed in detail, in Getting Started with Entitlements.
Frontegg’s Managed Audit Logs feature allows collecting custom audit logs that are specific for your application and displaying these in Frontegg's self-service component.
Create a new audits client
const { AuditsClient } = require('@frontegg/client'); const audits = new AuditsClient(); // initialize the module await audits.init('MY-CLIENT-ID', 'MY-AUDITS-KEY');
Sending audits
await audits.sendAudit({ tenantId: 'my-tenant-id', time: Date(), user: 'info@frontegg.com', resource: 'Portal', action: 'Login', severity: 'Medium', ip: '1.2.3.4', });
Fetching audits
const { data, total } = await audits.getAudits({ tenantId: 'my-tenant-id', filter: 'any-text-filter', sortBy: 'my-sort-field', sortDirection: 'asc | desc', offset: 0, // Offset for starting the page count: 50, // Number of desired items });
Working with the REST API
Frontegg provides a comprehensive REST API for your application. In order to use the API from your backend it is required to initialize the client and the authenticator which maintains the backend to backend session.
const authenticator = new FronteggAuthenticator(); await authenticator.init('<YOUR_CLIENT_ID>', '<YOUR_API_KEY>'); // You can optionally set the base url from the HttpClient const httpClient = new HttpClient(authenticator, { baseURL: 'https://api.frontegg.com' }); await httpClient.post( 'identity/resources/auth/v1/user', { email: 'johndoe@acme.com', password: 'my-super-duper-password', }, { // When providing vendor-host, it will replace(<...>) https://<api>.frontegg.com with vendor host 'frontegg-vendor-host': 'acme.frontegg', }, );
Validating JWT
Frontegg provides IdentityClient
that can be utilized for validating Frontegg JWTs.
- Import the
IdentityClient
const { IdentityClient } = require('@frontegg/client');
- Initialize the client
const identityClient = new IdentityClient({ FRONTEGG_CLIENT_ID: 'your-client-id', FRONTEGG_API_KEY: 'your-api-key' });
- Use this client to validate JWTs
app.use('/protected', (req, res, next) => { const token = req.headers.authorization; let user: IUser; try { user = identityClient.validateIdentityOnToken(token, { roles: ['admin'], permissions: ['read'] }); req.user = user; } catch (e) { console.error(e); next(e); return; } next(); });