@n1co/elements
Load n1co.js from npm in your web app, with TypeScript types. The script still comes from n1co's host.
- Install
@n1co/elementsin your web app. - Call
loadN1co(pk, { url })in the browser. - Mount the card element and confirm the payment as with n1co.js.
npm install @n1co/elementsThe package does not contain n1co.js. It adds n1co's hosted script to your page (once) and returns the n1co(publishableKey) client. Card details are still typed only in n1co's frames.
import { loadN1co } from '@n1co/elements';
import type { PaymentIntent } from '@n1co/elements';
export async function mountCheckout(form: HTMLFormElement, message: HTMLElement) {
const n1 = await loadN1co('pk_3x4mpl3pUbl1shabl3k3yAAAAAAAAAAA', {
url: 'https://elements.n1co.dev/v1/n1co.js', // development
});
if (!n1) return; // null during server-side rendering
const card = n1.elements().create('card', { locale: 'en' });
card.mount('#card');
form.addEventListener('submit', async (event) => {
event.preventDefault();
// Your server creates the intent with its secret key and returns only the client_secret.
const { client_secret } = await fetch('/checkout/payment-intent', { method: 'POST' }).then((r) => r.json());
try {
const intent: PaymentIntent = await n1.confirmPayment({ client_secret, card });
if (intent.status === 'succeeded') window.location.assign('/checkout/thanks');
else message.textContent = intent.last_error?.message ?? 'The payment could not be completed.';
} catch (error) {
message.textContent = (error as { message: string }).message;
}
});
}The client is the same as n1co.js: all its elements, options and errors are in the n1co.js reference. Your server confirms the payment with the webhook, as in Charge.
loadN1co options#
| Option | Value |
|---|---|
url |
Where n1co.js is loaded from. In development: https://elements.n1co.dev/v1/n1co.js. |
integrity |
The sha384-… of a pinned …/v1/n1co-<hash>.js URL. Not accepted with the floating one. |
Without url, the package uses the production host, which arrives with the production release. Always pass it for now.
If the page already loaded n1co.js with its own <script>, loadN1co uses that client.
Types#
It exports every public type of n1co.js: N1coClient, Element, CvcElement, CardOptionsInput, Appearance, ConfirmPaymentOptions, PaymentIntent, N1coError and more.
Common mistakes#
- Asking for another
urlorintegrity. Every call must use the same values as the first one, or as the page's<script>. Otherwise it rejects withinvalid_options: load n1co.js from a single module. - Using
instanceofon errors. The errors come from the hosted script. Compareerror.code:invalid_options,script_load_failed(a later call tries again) orinvalid_publishable_key. - A Content Security Policy without the host. Allow the n1co.js host in
script-srcandframe-src.
The package README has the loading details.