Embedded
Embedded authentication means using Knit’s drop-in web component <knit-auth>
UI – inside your own application. This allows your users to authenticate and authorize integrations directly within your product’s interface, rather than being redirected elsewhere.
Knit provides a pre-built widget (delivered as a single JS module) that you can embed in any web app (React, Angular, Vue, or plain JavaScript). This component handles all OAuth/API key forms for various apps and emits events so you can tie into the integration process.
General setup steps
- Include the Knit UI script. Add Knit's web component script to your app’s HTML. For example, in your main HTML file’s < head > include:
<script type="module" src="https://af1.getknit.dev/knit-ui-comp.js">
</script>
This imports the <knit-auth>
custom element (make sure to use a module script tag)
- Obtain an auth session token (backend). Before launching the UI, your backend must create an auth session for the user. Call the Knit Auth Session Creation API (auth.createSession) with the user’s identifiers to get a short-lived authSessionToken developers.getknit.dev. Never expose your API key in the frontend; retrieve this token on the server side.
- Render the
<knit-auth>
component in your front-end. In your application’s UI, add the<knit-auth>
element where the integration flow should be triggered. Inside it, include a button (or any element) withslot="trigger"
clicking this opens the Knit auth modal. Set the authsessiontoken attribute on<knit-auth>
to the token you got in step 2, so the component knows who is authorizing. - Handle component events. The Knit component emits events during the flow that you can listen for. Notably:
onNewSession
- emitted when the component needs a new session token (e.g. if the current token expires or a new integration flow is initiated). Your handler for this event should call your backend to fetch a newauthSessionToken
and assign it to the component.onFinish
- emitted when the user successfully finishes the integration setup. The event detail includes anintegrationDetails
object (with the new integration’s ID and info). You can use this to confirm success and inform your backend or UI (e.g., display “Connected!” to the user, and store theintegrationId
).onDeactivate
- emitted if the user disconnects or deactivates an integration via the UI. The detail contains theintegrationDetails
for the removed integration, so you can update your records.onKnitClose
- emitted if the user closes the auth modal without completing it. This can be used to detect a cancellation or simply to re-enable parts of your UI that were disabled during the modal.
You can attach event listeners in JavaScript or use your framework’s binding system to handle these events (examples below).
With those steps, your users will see a button in your app (the trigger), and clicking it will open a Knit-provided modal for selecting an app and authorizing it. After completion, you’ll get an integration ID just as with Magic Link, enabling API calls and syncs.
React Example
In a React application, you can integrate <knit-auth>
using a ref to control the component and React hooks for events. First, ensure the Knit JS script is included in your public HTML as described. Then in your component:
import { useEffect, useRef } from 'react';
function IntegrationWidget() {
const knitRef = useRef(null);
useEffect(() => {
// Fetch a new session token from backend and set it
const fetchToken = async () => {
const res = await fetch('/getSessionToken');
const data = await res.json();
if (knitRef.current) {
knitRef.current.setAttribute('authsessiontoken', data.token);
}
};
// Initial token fetch on mount
fetchToken();
// Define event handlers
const handleNewSession = (e) => {
e.preventDefault();
fetchToken(); // get a fresh token when onNewSession is emitted
};
const handleFinish = (e) => {
e.preventDefault();
const details = e.detail.integrationDetails;
console.log('Integration complete:', details);
// TODO: send details.integrationId to backend if needed
};
// Attach event listeners
const el = knitRef.current;
el.addEventListener('onNewSession', handleNewSession);
el.addEventListener('onFinish', handleFinish);
return () => {
// Cleanup listeners on unmount
el.removeEventListener('onNewSession', handleNewSession);
el.removeEventListener('onFinish', handleFinish);
};
}, []);
return (
<knit-auth ref={knitRef}>
<button slot="trigger">Connect an App</button>
</knit-auth>
);
}
In this example, the React component uses a ref to access the <knit-auth>
element. On mount, it fetches an auth session token from the backend and sets the authsessiontoken
attribute. It also listens for onNewSession
(to fetch a new token if the component requests one) and onFinish
(to log or handle the completed integration info). The button inside <knit-auth> with slot="trigger"
is what the user clicks to launch the modal.
Vanilla JavaScript Example
If you are not using a framework, you can still embed the Knit UI with plain HTML/JS:
<!-- Include the Knit UI web component script in your page -->
<script type="module" src="https://af1.getknit.dev/knit-ui-comp.js"></script>
<!-- Place the knit-auth component in your HTML -->
<knit-auth id="knitAuth">
<button slot="trigger">Connect with Knit</button>
</knit-auth>
<script>
const knitEl = document.getElementById('knitAuth');
// 1. Get an auth session token from your server and set it
fetch('/getSessionToken')
.then(res => res.json())
.then(data => {
knitEl.setAttribute('authsessiontoken', data.token);
});
// 2. Listen for completion event
knitEl.addEventListener('onFinish', event => {
const details = event.detail.integrationDetails;
console.log('Integration finished for app:', details.app.name, 'ID:', details.integrationId);
// TODO: notify server about new integration (details.integrationId)
});
// 3. (Optional) Listen for onNewSession to refresh token if needed
knitEl.addEventListener('onNewSession', () => {
// Fetch a new token and set it again
fetch('/getSessionToken')
.then(res => res.json())
.then(data => knitEl.setAttribute('authsessiontoken', data.token));
});
</script>
Here we directly manipulate the DOM. The <knit-auth id="knitAuth">
element is inserted with a trigger button. We fetch the authSessionToken
via an AJAX call and set it as an attribute on the element. We also add an event listener for onFinish
to react when the user completes the integration (logging the details or sending them to a backend). If another token is ever needed, the onNewSession
handler fetches a new one and updates the attribute.
Angular Example
In Angular, you can use the Knit component in your templates. Include the script in index.html as before. You may need to add CUSTOM_ELEMENTS_SCHEMA
to your AppModule so Angular allows the unknown <knit-auth>
element. Then, in a component, you can bind attributes and events:
app.component.html:
<knit-auth [authSessionToken]="token" (onFinish)="onFinish($event)" (onNewSession)="fetchToken()">
<button slot="trigger">Connect an App</button>
</knit-auth>
app.component.ts:
export class AppComponent {
token: string | null = null;
constructor(private http: HttpClient) {}
ngOnInit() {
this.fetchToken();
}
fetchToken(): void {
this.http.post<{ msg: { token: string } }>('/getSessionToken', {}).subscribe(res => {
this.token = res.msg.token;
});
}
onFinish(event: any): void {
const details = event.detail.integrationDetails;
console.log('Integration ID:', details.integrationId);
// ...handle integration completion (e.g., inform backend)
}
}
In the Angular template, we use property binding to set authSessionToken
from a component field, and event binding to handle onFinish
and onNewSession
. When the component initializes, it calls fetchToken()
which hits our backend for a token and sets the token property. That token is passed into <knit-auth>
via [authSessionToken
]. The (onNewSession)="fetchToken()"
binding means whenever the Knit UI needs a new token, it will call our method to retrieve one. The (onFinish)
binding calls onFinish() in our component, where we receive the integration details and can act on them. The trigger button is declared inside the element as in other examples.
Vue Example
For Vue 3 (composition API or options API), the setup is similar. Include the Knit script in index.html.
Then, in a Vue component:
IntegrationWidget.vue:
<template>
<knit-auth :authSessionToken="token" @onFinish="handleFinish" @onNewSession="fetchToken">
<button slot="trigger">Connect App</button>
</knit-auth>
</template>
<script>
export default {
data() {
return { token: null };
},
methods: {
async fetchToken() {
const res = await fetch('/getSessionToken');
const { msg } = await res.json();
this.token = msg.token;
},
handleFinish(event) {
const details = event.detail.integrationDetails;
console.log('Integration complete:', details);
// e.g., notify backend with details.integrationId
}
},
mounted() {
// Get initial token when component mounts
this.fetchToken();
}
}
</script>
In the template, we bind :authSessionToken
to a reactive token property. We listen for @onFinish
and @onNewSession
using Vue’s event syntax. The component’s logic (methods section) defines fetchToken to call our backend and update this.token, and handleFinish
to respond when an integration is done. On the mount, we call fetchToken()
so that the <knit-auth>
receives a token as soon as it renders.
Vue will reactively pass the updated token into the element attribute. When the user clicks "Connect App", the Knit modal opens (using the token). If Knit emits onNewSession
, we call fetchToken
again to update the token. When the flow finishes, handleFinish
logs the result (you would likely also update application state or inform your server).
Displaying Specific Apps Only
By default, the embedded Knit UI will show all available apps in the selected category for the user to choose from. However, you can limit the options to only specific apps (or even a single app) if your use case calls for it. This is done when creating the auth session token on the backend.
The auth. The createSession API accepts a filters parameter to restrict apps. For example, to show only Darwinbox (an HRIS app) in the UI, you would include a filter in the request body:
By default, the embedded Knit UI will show all available apps in the selected category for the user to choose from. However, you can limit the options to only specific apps (or even a single app) if your use case calls for it. This is done when creating the auth session token on the backend.
The auth. The createSession
API accepts a filters
parameter to restrict apps. For example, to show only Darwinbox (an HRIS app) in the UI, you would include a filter in the request body:
{
"originOrgId": "client1",
"originOrgName": "Client 1",
"originUserEmail": "[email protected]",
"originUserName": "User 1",
"filters": [
{
"apps": ["darwinbox"],
"category": "HRIS"
}
]
}
In the above, the filters array specifies an app by its identifier ("darwinbox") and its category ("HRIS"). The resulting auth session token will be tied to those filters. When used in the Knit UI, the component will display only the Darwinbox integration option and hide all others.
You can list multiple apps in the apps
array (within the same category) if you want to allow a specific subset. This feature is useful if, for instance, you want to embed a “Connect to X” button for a single known app, or limit choices to a few vendors that your platform supports.
For a full list of supported app IDs and categories, you can use the Knit API to retrieve them (see “Get List of Supported Apps” in the API reference).
Styling the Embedded Component
The embedded auth widget is designed to inherit your application’s look and feel. Knit provides multiple CSS custom properties (variables) to tweak the color palette and font, so the <knit-auth>
component can match your branding.
Key variables include things like --knit-primary
(primary brand color), --knit-secondary
, --knit-success
(success/confirmation color), --knit-failure
(error color), as well as --knit-font
for the font family.
By defining these in a CSS rule that applies to a parent element of <knit-auth>
(for example, on the <body>
or a container div
), you override the defaults.
For instance, you could add to your stylesheet:
/* Example: override Knit UI theme colors and font */
#app {
--knit-primary: rgb(47, 41, 99);
--knit-grey: rgb(149, 193, 203);
--knit-branding: rgb(255, 107, 107);
--knit-branding-alt: rgba(255, 244, 188, 0.48);
--knit-font: "Calibri", sans-serif;
}
This would change the primary interface color, some grayscale tones, the accent (“branding”) color, and the font family used by the Knit widget.
The component will then render with these choices (you can see an example of a custom-styled Knit UI in the docs).
In addition, you can customize the introductory screen’s content via the Knit dashboard. On the dashboard, under your integration settings or customization settings, you can upload your company’s logo, change the introductory text or bullet points shown to the user, and even set a custom Terms & Conditions URL for the “Accept terms” link getknit.dev.
Knit allows you to whitelabel the entire experience – you can replace the Knit logo with your own, adjust colors and fonts as described, and edit the text to suit your tone.
The next section provides a detailed how-to for whitelabeling the auth component.
Updated 18 days ago