GOV.UK Notify Node.js Client
The `notifications-node-client` is the official Node.js client library for interacting with the GOV.UK Notify API. It provides a programmatic interface for sending various types of government-related communications, including transactional emails, SMS messages, and physical letters. Currently at version 8.3.2, the library is actively maintained by alphagov, ensuring continuous compatibility with the GOV.UK Notify service and adherence to UK government security and accessibility standards. Releases typically align with Node.js LTS cycles or significant API updates. Its key differentiator is its direct, secure, and officially supported integration with the critical GOV.UK Notify infrastructure, making it indispensable for public sector applications in the UK that require reliable and compliant communication capabilities.
Common errors
-
Error: Invalid API key: not a valid UUID
cause The provided API key is either missing, malformed, or does not conform to the UUID format expected by GOV.UK Notify.fixDouble-check your API key for typos and ensure it's correctly copied from your GOV.UK Notify account. Verify that the environment variable holding the key is correctly loaded. -
Error: Missing template ID
cause The `templateId` parameter was not provided to `sendEmail`, `sendSms`, or `sendLetter` methods, or it was `null`/`undefined`.fixEnsure that a valid template ID string is passed as the first argument to the `sendEmail`, `sendSms`, or `sendLetter` method. These IDs are found in your GOV.UK Notify account. -
Error: Can't send to this recipient using a team-only API key
cause You are attempting to send a notification to a recipient that is not on your team when using an API key that is restricted to 'team members only' (often a test key or development key).fixFor production or sending to external recipients, ensure you are using an API key with appropriate permissions (usually a 'live' or 'production' key). For testing, add the recipient's email/phone number to your team in the GOV.UK Notify admin interface. -
TypeError: notifyClient.sendEmail is not a function
cause This usually indicates that `notifyClient` was not correctly instantiated as a `NotifyClient` instance, or the import/require statement was incorrect, leading to `notifyClient` being `undefined` or a malformed object.fixVerify that `new NotifyClient(API_KEY)` is called correctly. If using CommonJS, ensure `const { NotifyClient } = require('notifications-node-client');`. If using ESM, ensure `import { NotifyClient } from 'notifications-node-client';`.
Warnings
- breaking Version 8.0.0 and above significantly changed the response object structure due to replacing `request-promise` with `axios`. Successful API calls now return an `axios` response, meaning `response.body` becomes `response.data` and `response.statusCode` becomes `response.status`. Error objects also have a different interface.
- breaking Versions prior to 8.x.x (specifically, version 7.x.x and earlier) dropped support for Node.js versions below v12. The package now explicitly requires Node.js `>=14.17.3` as per `engines` field, which means older Node.js runtimes are not officially supported and may lead to unexpected behavior or errors.
- gotcha GOV.UK Notify API keys are highly sensitive. Hardcoding them directly in your source code or checking them into version control is a major security vulnerability. Doing so could lead to unauthorized access to your Notify account and misuse of your communication quotas.
- deprecated Older versions of the client (prior to v8) used `request-promise` which is now deprecated. While direct client usage typically wouldn't expose this, relying on internal `request-promise` specifics in custom wrapper code would be affected. The client moved to `axios` in v8.x.x.
Install
-
npm install notifications-node-client -
yarn add notifications-node-client -
pnpm add notifications-node-client
Imports
- NotifyClient
const { NotifyClient } = require('notifications-node-client');import { NotifyClient } from 'notifications-node-client'; - NotifyClient
import NotifyClient from 'notifications-node-client';
const { NotifyClient } = require('notifications-node-client'); - NotificationClientOptions
import { NotificationClientOptions } from 'notifications-node-client';import type { NotificationClientOptions } from 'notifications-node-client';
Quickstart
import { NotifyClient } from 'notifications-node-client';
// Ensure you set your GOV.UK Notify API key in an environment variable
const API_KEY = process.env.GOVUK_NOTIFY_API_KEY ?? 'your-api-key';
// Instantiate the client
const notifyClient = new NotifyClient(API_KEY);
// Example: Sending an email
async function sendExampleEmail() {
const emailAddress = 'test@example.com';
const templateId = 'your-email-template-id'; // Replace with your actual template ID
const personalisation = {
name: 'John Doe',
application_status: 'approved',
};
const reference = 'my-email-ref-123'; // Optional unique reference
try {
console.log(`Attempting to send email to ${emailAddress} using template ${templateId}...`);
const response = await notifyClient.sendEmail(
templateId,
emailAddress,
personalisation,
reference
);
console.log('Email sent successfully!');
console.log('Response:', JSON.stringify(response.data, null, 2));
} catch (error: any) {
console.error('Failed to send email:');
// GOV.UK Notify errors often have a 'response.data.errors' structure
if (error.response && error.response.data && error.response.data.errors) {
console.error('API Error Details:', JSON.stringify(error.response.data.errors, null, 2));
} else {
console.error(error.message || error);
}
process.exit(1);
}
}
// Example: Sending an SMS
async function sendExampleSms() {
const phoneNumber = '+447900900123'; // Replace with a valid UK phone number
const templateId = 'your-sms-template-id'; // Replace with your actual template ID
const personalisation = {
verification_code: '123456',
};
const reference = 'my-sms-ref-456'; // Optional unique reference
try {
console.log(`Attempting to send SMS to ${phoneNumber} using template ${templateId}...`);
const response = await notifyClient.sendSms(
templateId,
phoneNumber,
personalisation,
reference
);
console.log('SMS sent successfully!');
console.log('Response:', JSON.stringify(response.data, null, 2));
} catch (error: any) {
console.error('Failed to send SMS:');
if (error.response && error.response.data && error.response.data.errors) {
console.error('API Error Details:', JSON.stringify(error.response.data.errors, null, 2));
} else {
console.error(error.message || error);
}
process.exit(1);
}
}
// Run the examples (uncomment to execute)
// sendExampleEmail();
// sendExampleSms();