Pexels JavaScript Client

1.4.0 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

Demonstrates initializing the Pexels client with an API key and fetching curated photos, handling potential errors and types.

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();

view raw JSON →