{"id":11547,"library":"pexels","title":"Pexels JavaScript Client","description":"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.","status":"active","version":"1.4.0","language":"javascript","source_language":"en","source_url":"https://github.com/pexels/pexels-javascript","tags":["javascript","typescript"],"install":[{"cmd":"npm install pexels","lang":"bash","label":"npm"},{"cmd":"yarn add pexels","lang":"bash","label":"yarn"},{"cmd":"pnpm add pexels","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Provides a consistent `fetch` API across Node.js and browser environments for making HTTP requests to the Pexels API.","package":"isomorphic-fetch","optional":false}],"imports":[{"note":"The primary entry point for initializing the Pexels client. Named import is standard for ESM.","wrong":"const createClient = require('pexels').createClient;","symbol":"createClient","correct":"import { createClient } from 'pexels';"},{"note":"Use `import type` for TypeScript interfaces to ensure they are removed during compilation, avoiding runtime overhead.","wrong":"import { Photo } from 'pexels';","symbol":"Photo","correct":"import type { Photo } from 'pexels';"},{"note":"Type import for video objects returned by the API. Follows standard TypeScript best practices.","wrong":"import { Video } from 'pexels';","symbol":"Video","correct":"import type { Video } from 'pexels';"}],"quickstart":{"code":"import { createClient } from 'pexels';\nimport type { Photo } from 'pexels';\n\nconst PEXELS_API_KEY = process.env.PEXELS_API_KEY ?? '';\n\nif (!PEXELS_API_KEY) {\n  console.error('PEXELS_API_KEY environment variable is not set.');\n  process.exit(1);\n}\n\nconst client = createClient(PEXELS_API_KEY);\n\nasync function fetchCuratedPhotos() {\n  try {\n    const query = 'nature';\n    const photos = await client.photos.search({ query, per_page: 1 });\n\n    if ('photos' in photos) {\n      console.log(`Found ${photos.total_results} photos for '${query}'.`);\n      if (photos.photos.length > 0) {\n        const firstPhoto: Photo = photos.photos[0];\n        console.log('First photo ID:', firstPhoto.id);\n        console.log('Photographer:', firstPhoto.photographer);\n        console.log('Original image URL:', firstPhoto.src.original);\n      } else {\n        console.log('No photos found for the query.');\n      }\n    } else {\n      console.error('API Error:', photos);\n    }\n  } catch (error) {\n    console.error('An unexpected error occurred:', error);\n  }\n}\n\nfetchCuratedPhotos();","lang":"typescript","description":"Demonstrates initializing the Pexels client with an API key and fetching curated photos, handling potential errors and types."},"warnings":[{"fix":"Ensure your error handling explicitly catches exceptions thrown by API calls, rather than relying solely on checking properties like `response.ok` on the returned object.","message":"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.","severity":"breaking","affected_versions":">=1.3.0"},{"fix":"Obtain an API key from Pexels (https://www.pexels.com/api/new/) and pass it to `createClient()`. For production, use environment variables (`process.env.PEXELS_API_KEY`) to manage keys securely.","message":"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.","severity":"gotcha","affected_versions":">=1.0.1"},{"fix":"Always use `import type { Photo, Video } from 'pexels';` when importing only type definitions.","message":"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.","severity":"gotcha","affected_versions":">=1.0.1"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `createClient('YOUR_API_KEY')` is called with a valid Pexels API key. Verify the key is correct and accessible (e.g., from environment variables).","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.","error":"TypeError: Cannot read properties of undefined (reading 'photos')"},{"fix":"Check 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.","cause":"The provided Pexels API Key is either missing, incorrect, or expired.","error":"Error: Request failed with status code 401"},{"fix":"Change your import statement to `import type { Photo } from 'pexels';` for type definitions.","cause":"Attempting to import a TypeScript interface (`Photo`, `Video`) using a regular named import (`import { Photo } from 'pexels';`) instead of a type-only import.","error":"TS2305: Module '\"pexels\"' has no exported member 'Photo'."}],"ecosystem":"npm"}