Unsplash JavaScript API Wrapper
unsplash-js is the official JavaScript wrapper for the Unsplash API, providing a convenient way to interact with Unsplash's photo services. The library abstracts away direct HTTP requests, offering methods for accessing photos, users, collections, and search functionalities. The current stable version is 7.0.20. Historically, it saw frequent minor updates for new API features and bug fixes, as evidenced by the recent v7.0.x releases. However, as of the latest README, the project has been officially archived and no longer receives support or updates, meaning new API features from Unsplash will not be integrated into this library, and critical bug fixes are unlikely. Developers are now directed to use the Unsplash developer documentation to make requests directly to the API, rather than relying on this wrapper.
Common errors
-
ReferenceError: fetch is not defined
cause The runtime environment (typically Node.js) does not have a global `fetch` function available, and no polyfill was provided.fixInstall `node-fetch` (`npm install node-fetch`) and set it globally (`global.fetch = require('node-fetch');`) or pass it directly to `createApi`: `createApi({ accessKey: 'YOUR_KEY', fetch: require('node-fetch') });` -
Argument of type 'typeof import("node-fetch")' is not assignable to parameter of type 'typeof fetch'.cause TypeScript type conflict when passing `node-fetch` to `createApi`, especially with `node-fetch` v3, due to differing global type definitions or incorrect import/assignment.fixUse a type assertion when passing `node-fetch.default`: `fetch: nodeFetch.default as unknown as typeof fetch,`. -
Error: Request failed with status code 401. 'The access key provided is invalid.'
cause The `accessKey` configured for `unsplash-js` is incorrect, expired, or missing required permissions.fixDouble-check your Unsplash developer account for the correct 'Access Key' and ensure it's properly configured in your application. Register as a developer if you haven't already.
Warnings
- breaking The `unsplash-js` project has been officially archived and is no longer maintained. It will not receive updates, new features, or bug fixes. Developers should transition to direct API calls using the Unsplash developer documentation.
- gotcha This library depends on the `fetch` API. In Node.js environments, you must provide a polyfill like `node-fetch`, either globally or explicitly when calling `createApi`.
- gotcha When using `node-fetch` v3 with TypeScript, there's a known incompatibility where `node-fetch` pollutes the global namespace with 'dom' type definitions, causing conflicts with `unsplash-js`'s expectation of global `fetch`, `RequestInit`, and `Response` types.
- gotcha Adherence to Unsplash API Guidelines is mandatory. This includes hotlinking images, attributing photographers, and triggering a download when appropriate.
Install
-
npm install unsplash-js -
yarn add unsplash-js -
pnpm add unsplash-js
Imports
- createApi
const { createApi } = require('unsplash-js');import { createApi } from 'unsplash-js'; - NodeFetch
import { fetch } from 'node-fetch';import nodeFetch from 'node-fetch';
- RequestInit, Response
type RequestInit = nodeFetch.RequestInit; type Response = nodeFetch.Response;
Quickstart
import { createApi } from 'unsplash-js';
import nodeFetch from 'node-fetch';
// Ensure global fetch types are available for TypeScript in Node.js
declare global {
var fetch: typeof nodeFetch.default;
type RequestInit = nodeFetch.RequestInit;
type Response = nodeFetch.Response;
}
// Set global fetch for Node.js if not already present
if (typeof global !== 'undefined' && !global.fetch) {
global.fetch = nodeFetch.default;
}
const MY_ACCESS_KEY = process.env.UNSPLASH_ACCESS_KEY ?? '';
if (!MY_ACCESS_KEY) {
console.error('UNSPLASH_ACCESS_KEY environment variable is not set.');
process.exit(1);
}
const unsplash = createApi({
accessKey: MY_ACCESS_KEY,
// Optional: Provide node-fetch explicitly if not setting globally, or for type compatibility
fetch: nodeFetch.default as unknown as typeof fetch,
});
async function getRandomPhoto() {
try {
const result = await unsplash.photos.getRandom({
count: 1,
orientation: 'landscape',
});
if (result.type === 'success' && result.response.length > 0) {
const photo = result.response[0];
console.log('Random Photo:', photo.urls.regular);
console.log('Photographer:', photo.user.name);
console.log('Download URL (trigger download):', photo.links.download_location);
} else if (result.type === 'error') {
console.error('Failed to fetch random photo:', result.errors);
}
} catch (error) {
console.error('An unexpected error occurred:', error);
}
}
getRandomPhoto();