Pexels JavaScript Client
The Pexels JavaScript client is an official, actively maintained wrapper for the Pexels API, designed to simplify interactions for both Node.js and browser environments. Currently stable at version 1.4.0, it provides a fluent interface for accessing Pexels' vast collection of photos and videos, including curated content and search functionality. Recent releases indicate a steady cadence of updates, including new API endpoint support (e.g., collections) and type enhancements for a robust TypeScript experience. Its key differentiator is being the officially supported client, ensuring alignment with the Pexels API and consistent maintenance. It internally utilizes `isomorphic-fetch` to provide a consistent fetching mechanism across different JavaScript runtimes.
Common errors
-
TypeError: Cannot read properties of undefined (reading 'photos')
cause The `createClient` function was not properly called with an API key, or the key was invalid, leading to an uninitialized or failed client instance.fixEnsure `createClient('YOUR_API_KEY')` is called with a valid Pexels API key. Verify the key is correct and accessible (e.g., from environment variables). -
Error: Request failed with status code 401
cause The provided Pexels API Key is either missing, incorrect, or expired.fixCheck your API key. Ensure it's correctly copied, active, and passed to `createClient()`. You can generate a new one at https://www.pexels.com/api/new/ if needed. -
TS2305: Module '"pexels"' has no exported member 'Photo'.
cause Attempting to import a TypeScript interface (`Photo`, `Video`) using a regular named import (`import { Photo } from 'pexels';`) instead of a type-only import.fixChange your import statement to `import type { Photo } from 'pexels';` for type definitions.
Warnings
- breaking As of v1.3.0, the client now throws an error when the API response is not `ok`. Previously, it might have returned a non-success response object that required manual checking.
- gotcha An API Key is mandatory for almost all interactions with the Pexels API. Attempts to use the client without a valid key will result in authentication errors.
- gotcha While the library ships TypeScript types, it's crucial to use `import type` for interfaces (e.g., `Photo`, `Video`) to prevent them from being bundled into your JavaScript output, which can increase payload size unnecessarily.
Install
-
npm install pexels -
yarn add pexels -
pnpm add pexels
Imports
- createClient
const createClient = require('pexels').createClient;import { createClient } from 'pexels'; - Photo
import { Photo } from 'pexels';import type { Photo } from 'pexels'; - Video
import { Video } from 'pexels';import type { Video } from 'pexels';
Quickstart
import { createClient } from 'pexels';
import type { Photo } from 'pexels';
const PEXELS_API_KEY = process.env.PEXELS_API_KEY ?? '';
if (!PEXELS_API_KEY) {
console.error('PEXELS_API_KEY environment variable is not set.');
process.exit(1);
}
const client = createClient(PEXELS_API_KEY);
async function fetchCuratedPhotos() {
try {
const query = 'nature';
const photos = await client.photos.search({ query, per_page: 1 });
if ('photos' in photos) {
console.log(`Found ${photos.total_results} photos for '${query}'.`);
if (photos.photos.length > 0) {
const firstPhoto: Photo = photos.photos[0];
console.log('First photo ID:', firstPhoto.id);
console.log('Photographer:', firstPhoto.photographer);
console.log('Original image URL:', firstPhoto.src.original);
} else {
console.log('No photos found for the query.');
}
} else {
console.error('API Error:', photos);
}
} catch (error) {
console.error('An unexpected error occurred:', error);
}
}
fetchCuratedPhotos();