@ibaraki-douji/pixivts
v3.1.0
Published
A TypeScript/JavaScript SDK for the Pixiv API, providing easy access to illustrations, novels, user data, and more.
Maintainers
Readme
@ibaraki-douji/pixivts
A TypeScript/JavaScript SDK for the Pixiv API, providing easy access to illustrations, novels, user data, and more.
Features
- 🎨 Illustrations API - Search, browse rankings, get details, ugoira metadata
- 📚 Novels API - Access Pixiv's novel content and search functionality
- 👤 Users API - User profiles, works, bookmarks, and search
- 🔐 Account API - Authentication, recommendations, notifications, and personal content
- 🏷️ Tags API - Tag autocomplete and trending tags
- 🔒 TypeScript Support - Full type definitions included
- ✅ Well Tested - Comprehensive test suite with coverage reporting
Installation
npm install @ibaraki-douji/pixivtsOptional Dependencies
For username/password and cookie authentication methods (new in v3.1.0):
npm install puppeteer puppeteer-extra puppeteer-extra-plugin-stealthNote: These optional dependencies are only required if you plan to use the new authentication methods introduced in version 3.1.0. Refresh token authentication (the recommended method) works without these packages.
Quick Start
import { Pixiv, Illusts, Users, Novels, Account, Tags } from '@ibaraki-douji/pixivts';
async function main() {
// Initialize the client
const pixiv = new Pixiv();
// Option 1: Login with refresh token
await pixiv.login('your_refresh_token_here');
// Option 2: Login with username/password (requires puppeteer packages)
// await pixiv.login('your_username', 'your_password');
// Option 3: Login with cookies and user agent (requires puppeteer packages)
// const cookies = 'your_browser_cookies_here';
// const userAgent = 'your_browser_user_agent_here';
// await pixiv.login(cookies, userAgent);
// Create API clients
const illusts = new Illusts(pixiv);
const users = new Users(pixiv);
const novels = new Novels(pixiv);
const account = new Account(pixiv);
const tags = new Tags(pixiv);
// Get daily ranking illustrations
const ranking = await illusts.getRankingIllusts('day');
console.log(`Found ${ranking.length} illustrations`);
// Get a specific illustration
const illust = await illusts.getIllustById(127771357);
console.log(`Title: ${illust.title} by ${illust.user.name}`);
// Get user profile
const user = await users.getUser(123456);
console.log(`User: ${user.user.name}`);
// Get tag suggestions
const tagSuggestions = await tags.tagAutocomplete('anime');
console.log(`Found ${tagSuggestions.length} tag suggestions`);
}
main().catch(console.error);Authentication
The SDK supports three authentication methods to suit different use cases and security requirements:
- Refresh Token Authentication - Most reliable and recommended for production use
- Username/Password Authentication - Direct credential login with automated browser
- Cookie Authentication - Uses existing browser session cookies (headless-compatible)
Each method has its own advantages and requirements detailed below.
Method 1: Refresh Token Authentication
To authenticate with a refresh token, you can obtain one by:
- Using the Pixiv mobile app and intercepting network requests
- Using tools like
gppt(Get Pixiv Token)
Note: Keep your refresh token secure and never share it publicly.
const pixiv = new Pixiv({
hosts: 'https://app-api.pixiv.net', // Optional: custom API host
autoRenewAuth: true // Optional: automatically renew authentication (default: true)
});
// Login with refresh token
await pixiv.login('your_refresh_token_here');
// Logout when done (optional)
await pixiv.logout();Method 2: Username/Password Authentication
For direct username and password authentication, the SDK uses automated browser login to obtain authentication tokens. This method requires additional dependencies.
Prerequisites
Install the required packages for browser automation:
npm install puppeteer puppeteer-extra puppeteer-extra-plugin-stealthLogin with Username/Password
const pixiv = new Pixiv({
autoRenewAuth: true // Optional: automatically renew authentication (default: true)
});
// In case you want to run the browser without headless
pixiv['headless'] = false; // or 'shell' for non-headless mode
// In my tests, only 'false' works reliably
// Login with username and password
await pixiv.login('your_username', 'your_password');
// After successful login, you can access the refresh token for future use
console.log('Refresh Token:', pixiv['refreshToken']);
// Logout when done (optional)
await pixiv.logout();If Pixiv presents a CAPTCHA, the process may require manual intervention
Saving Refresh Token for Future Use
After successful username/password login, save the refresh token to avoid repeated browser automation:
import { writeFileSync, readFileSync } from 'fs';
// Login once with username/password
await pixiv.login('username', 'password');
// Save refresh token
writeFileSync('refresh_token.txt', pixiv['refreshToken']);
// In future sessions, use the saved refresh token
const savedRefreshToken = readFileSync('refresh_token.txt', 'utf8');
await pixiv.login(savedRefreshToken);Method 3: Cookie/User-Agent Authentication
For users who have browser session cookies and user agent information, the SDK supports direct cookie-based authentication. This method is more reliable than username/password authentication and works with headless mode enabled.
Prerequisites
Install the required packages for browser automation:
npm install puppeteer puppeteer-extra puppeteer-extra-plugin-stealthRetrieve your Pixiv session cookies and user agent string from your browser's developer tools.
Login with Cookies and User Agent
const pixiv = new Pixiv({
autoRenewAuth: true // Optional: automatically renew authentication (default: true)
});
// This method works with headless mode enabled (default)
pixiv['headless'] = true; // Headless mode is supported with cookie authentication
// Login with cookies and user agent
const cookies = 'your_browser_cookies_here'; // Format: "name1=value1; name2=value2; ..."
const userAgent = 'your_browser_user_agent_here'; // Full user agent string from your browser
await pixiv.login(cookies, userAgent);
// After successful login, you can access the refresh token for future use
console.log('Refresh Token:', pixiv['refreshToken']);
// Logout when done (optional)
await pixiv.logout();Note: Cookie authentication may still encounter Cloudflare protection or CAPTCHA challenges depending on various factors including IP reputation, session age, and Pixiv's security measures. Success rates may vary between users and over time.
Saving Refresh Token for Future Use
After successful cookie-based login, save the refresh token to avoid repeated cookie extraction:
import { writeFileSync, readFileSync } from 'fs';
// Login once with cookies
await pixiv.login(cookies, userAgent);
// Save refresh token
writeFileSync('refresh_token.txt', pixiv['refreshToken']);
// In future sessions, use the saved refresh token
const savedRefreshToken = readFileSync('refresh_token.txt', 'utf8');
await pixiv.login(savedRefreshToken);API Reference
Illustrations
const illusts = new Illusts(pixiv);
// Get ranking illustrations
const daily = await illusts.getRankingIllusts('day', 1);
const weekly = await illusts.getRankingIllusts('week', 1);
const monthly = await illusts.getRankingIllusts('month', 1);
// Available ranking modes
type RankingMode =
| 'day'
| 'week'
| 'month'
| 'day_male'
| 'day_female'
| 'day_ai'
| 'week_original'
| 'week_rookie';
// Get specific illustration
const illust = await illusts.getIllustById(12345);
// Get newest illustrations and manga
const newestIllusts = await illusts.getNewestIllusts(1);
const newestMangas = await illusts.getNewestMangas(1);
// Get ugoira (animated illustration) metadata
const ugoiraData = await illusts.getUgoiraMetadata(12345);
// Search illustrations
const results = await illusts.searchIllusts('keyword', 1, {
include_translated_tag_results: true,
merge_plain_keyword_results: true,
with_ai: false // Set to true to include AI-generated content
});Users
const users = new Users(pixiv);
// Get user profile
const profile = await users.getUser(123456);
// Get user's works
const userIllusts = await users.getUserIllusts(123456, 'illust', 1);
const userMangas = await users.getUserIllusts(123456, 'manga', 1);
const userNovels = await users.getUserNovels(123456, 1);
// Get user's bookmarks
const bookmarkedIllusts = await users.getUserBookmarkedIllusts(123456, 1);
const bookmarkedNovels = await users.getUserBookmarkedNovels(123456, 1);
// Get user's request plans (commission info)
const requestPlans = await users.getUserRequestPlans(123456);
// Search users
const userResults = await users.searchUsers('artist_name', 1);Novels
const novels = new Novels(pixiv);
// Get newest novels
const newest = await novels.getNewestNovels();
// Search novels
const results = await novels.searchNovels('keyword', 1, {
include_translated_tag_results: true,
merge_plain_keyword_results: true,
with_ai: false // Set to true to include AI-generated content
});Account
import { Account } from '@ibaraki-douji/pixivts';
const account = new Account(pixiv);
// Get current user info
const userInfo = await account.getSelfUser();
// Get your bookmarks
const illustBookmarks = await account.getSelfBookmarks('illust', 1);
const novelBookmarks = await account.getSelfBookmarks('novel', 1);
// Get user state information
const userState = await account.getUserState();
// Get personalized recommendations
const recommendedIllusts = await account.getRecommendedIllusts(1);
const recommendedMangas = await account.getRecommendedMangas(1);
const recommendedNovels = await account.getRecommendedNovels(1);
const recommendedUsers = await account.getRecommendedUsers(1);
// Get content from followed users
const followIllusts = await account.getFollowIllusts(1);
const followNovels = await account.getFollowNovels(1);
// Get your watchlists
const mangaWatchlist = await account.getMangaWatchlist(1);
const novelWatchlist = await account.getNovelWatchlist(1);
// Get notifications
const notifications = await account.getNotifications(1);
const hasUnread = await account.hasUnreadNotifications();Tags
import { Tags } from '@ibaraki-douji/pixivts';
const tags = new Tags(pixiv);
// Get tag autocomplete suggestions
const suggestions = await tags.tagAutocomplete('anime');
// Get trending tags
const trendingIllustTags = await tags.getTrendingTags('illust');
const trendingNovelTags = await tags.getTrendingTags('novel');Types
The SDK includes comprehensive TypeScript definitions:
import {
Illust,
Novel,
User,
UserProfile,
UserPreview,
UserState,
Tag,
TrendTag,
UgoiraMetadata,
Series,
RequestPlan,
ImageUrls
} from '@ibaraki-douji/pixivts';Error Handling
Version 3.1.0 introduces enhanced error handling with detailed error information:
import { PixivError } from '@ibaraki-douji/pixivts';
try {
const illust = await illusts.getIllustById(12345);
} catch (error) {
if (error instanceof PixivError) {
console.error('Pixiv API Error:', error.message);
console.error('HTTP Status:', error.status);
console.error('Response:', error.response);
// For authentication errors (4xx/5xx status codes)
if (error.status >= 400) {
console.error('Authentication or API error occurred');
}
} else if (error instanceof Error) {
console.error('Network or other error:', error.message);
}
}Rate Limiting
Be respectful of Pixiv's servers:
- Don't make too many concurrent requests
- Add delays between requests when making bulk operations
- Consider caching responses when appropriate
// Example: Adding delay between requests
const illustIds = [12345, 67890, 54321];
for (const illustId of illustIds) {
const illust = await illusts.getIllustById(illustId);
console.log(`Got: ${illust.title}`);
// Add 1 second delay
await new Promise(resolve => setTimeout(resolve, 1000));
}Development
Building
npm run buildTesting
# Run all tests
npm test
# Run tests with coverage report
npm run test:covScripts
npm run build- Compile TypeScript to JavaScriptnpm start- Build and run the main filenpm test- Run the test suitenpm run test:cov- Run tests with coverage reporting
Project Structure
src/
├── client/ # API client classes
│ ├── Pixiv.ts # Core client with authentication
│ ├── Illusts.ts # Illustrations API
│ ├── Novels.ts # Novels API
│ ├── Users.ts # Users API
│ ├── Account.ts # Account API
│ └── Tags.ts # Tags API
├── types/ # TypeScript type definitions
│ ├── Common.ts # Shared types (Tag, TrendTag, ImageUrls)
│ ├── Illust.ts # Illustration-related types
│ ├── Novel.ts # Novel-related types
│ ├── User.ts # User-related types
│ ├── UgoiraMetadata.ts # Ugoira animation types
│ ├── RequestPlan.ts # Commission/request types
│ └── PixivError.ts # Custom error class
├── index.ts # Main exports
└── main.ts # Development/testing entry pointDependencies
- Runtime:
node-fetchfor HTTP requests,tslibfor TypeScript helpers - Development: Jest for testing, TypeScript compiler, type definitions
- Optional:
puppeteer,puppeteer-extra,puppeteer-extra-plugin-stealthfor username/password authentication
Bugs / Feature Requests
Please head to the Discord server.
