To integrate the Pixabay API with V0 by Vercel, create a Next.js API route that proxies image and video search requests to Pixabay, store your API key in Vercel environment variables, and use V0 to generate a searchable image gallery component. Pixabay provides free stock images and videos with a generous API rate limit.
Add a Free Stock Image Search Gallery to Your V0 App with Pixabay
Pixabay offers one of the most accessible free stock image APIs available: over 4 million royalty-free photos, illustrations, vectors, and videos — all free to use commercially without attribution required (though appreciated). The Pixabay API is a straightforward JSON REST API that requires only a free API key and supports full-text search, category filtering, color filtering, and orientation options.
When building apps with V0 by Vercel, you can integrate Pixabay to add image search capabilities to content creation tools, blog editors, marketing dashboards, or any app where users need to find and embed free stock images without leaving your interface. The integration is relatively simple compared to paid stock image APIs: there is no OAuth flow, no per-download billing, and no complex license management.
The recommended architecture for a V0 app is to proxy Pixabay requests through a Next.js API route. While technically you could call the Pixabay API directly from the browser (since it uses a query parameter for auth), doing so exposes your API key in the browser's network tab. A server-side proxy takes only a few minutes to set up and protects your key from abuse. V0 generates the gallery UI component, and your Next.js API route handles the actual Pixabay communication.
Integration method
The Pixabay API is a simple REST API that accepts your API key as a query parameter. Because exposing the key in browser requests is a security risk, you proxy all Pixabay calls through a Next.js API route that reads the key from a server-side environment variable. Your V0-generated gallery component fetches search results from your own secure route.
Prerequisites
- A free Pixabay account and API key — register at pixabay.com and get your key at pixabay.com/api/docs/
- A V0 account at v0.dev for generating gallery UI components
- A Vercel account to deploy the Next.js application
- Basic understanding of React hooks (useState, useEffect) for handling search state
Step-by-step guide
Generate the Image Gallery UI with V0
Generate the Image Gallery UI with V0
Start in V0 by crafting a prompt that describes your gallery component in detail. The Pixabay API returns image objects with fields including previewURL (small thumbnail), webformatURL (medium display size), largeImageURL (full resolution), tags (comma-separated keywords), user (photographer name), views, and downloads. Your V0 prompt should reference these fields so the generated component knows what data to display. A well-designed gallery needs a search input, a loading state (skeleton cards or spinner), an error state, a results grid with proper image aspect ratios, and pagination or infinite scroll. V0 can generate all of these in one prompt if you are specific. After V0 generates the component, push it to GitHub via the Git panel and let Vercel auto-deploy. The component will show empty/mock state until the API route is connected.
Create an image search gallery with a search bar at the top with a search button. Below it, show a responsive masonry-style grid with 3 columns on desktop and 2 on mobile. Each card shows the image (using webformatURL), photographer name at the bottom, and view/download counts. Add a loading state with 9 skeleton cards, an empty state for no results, and next/previous pagination buttons. Fetch from /api/pixabay?q={query}&page={page}&per_page=21.
Paste this in V0 chat
Pro tip: Ask V0 to use the Next.js Image component for the gallery thumbnails instead of plain img tags. This enables lazy loading and automatic WebP conversion, which significantly improves page performance for image-heavy galleries.
Expected result: A styled image gallery component renders in the V0 preview with skeleton loading state, empty state message, and pagination buttons. The search input is functional but returns no results until the API route is connected.
Create the Pixabay API Route
Create the Pixabay API Route
Create a Next.js API route that receives search parameters from your gallery component and forwards the request to the Pixabay API with your secret API key appended. The Pixabay API is at https://pixabay.com/api/ for images and https://pixabay.com/api/videos/ for videos. It accepts query parameters including q (search query), image_type (photo, illustration, vector, all), category, colors, orientation, per_page (max 200, default 20), and page. The key parameter is your API key. One important note about Pixabay API: the total hits field is capped at 500 results regardless of the real total. This means your pagination should stop at page ceil(500 / per_page). Build this limit into the component to avoid showing a Next Page button when no more results exist. The route below handles both image and video searches with a single endpoint.
1import { NextRequest, NextResponse } from 'next/server';23const PIXABAY_API_BASE = 'https://pixabay.com/api';45export async function GET(request: NextRequest) {6 const apiKey = process.env.PIXABAY_API_KEY;7 if (!apiKey) {8 return NextResponse.json({ error: 'Pixabay API key not configured' }, { status: 500 });9 }1011 const { searchParams } = new URL(request.url);12 const q = searchParams.get('q') ?? '';13 const imageType = searchParams.get('image_type') ?? 'all';14 const category = searchParams.get('category') ?? '';15 const orientation = searchParams.get('orientation') ?? 'all';16 const perPage = Math.min(parseInt(searchParams.get('per_page') ?? '21', 10), 200);17 const page = Math.max(parseInt(searchParams.get('page') ?? '1', 10), 1);18 const mediaType = searchParams.get('media_type') ?? 'images'; // 'images' or 'videos'1920 const baseUrl = mediaType === 'videos'21 ? `${PIXABAY_API_BASE}/videos/`22 : `${PIXABAY_API_BASE}/`;2324 const params = new URLSearchParams({25 key: apiKey,26 q,27 image_type: imageType,28 orientation,29 per_page: perPage.toString(),30 page: page.toString(),31 safesearch: 'true',32 lang: 'en',33 });3435 if (category) params.append('category', category);3637 try {38 const response = await fetch(`${baseUrl}?${params.toString()}`);3940 if (!response.ok) {41 return NextResponse.json(42 { error: `Pixabay API error: ${response.status}` },43 { status: response.status }44 );45 }4647 const data = await response.json();48 return NextResponse.json(data, {49 headers: {50 'Cache-Control': 's-maxage=300, stale-while-revalidate=600',51 },52 });53 } catch (error) {54 console.error('Pixabay API route error:', error);55 return NextResponse.json({ error: 'Failed to fetch from Pixabay' }, { status: 500 });56 }57}Pro tip: The Cache-Control header in the response caches results for 5 minutes on Vercel's CDN. Since Pixabay search results for a given query rarely change minute-to-minute, this caching significantly reduces API calls without affecting freshness.
Expected result: The API route is created. You can test it at /api/pixabay?q=nature&per_page=9 in your browser after adding the API key in the next step. You should see a JSON response with a hits array of image objects from Pixabay.
Add the Pixabay API Key to Vercel
Add the Pixabay API Key to Vercel
Register for a free Pixabay account at pixabay.com if you have not already, then navigate to pixabay.com/api/docs/ while logged in to find your personal API key at the top of the page. The key is a string of numbers. Add it to Vercel as an environment variable: open your Vercel project dashboard, go to Settings → Environment Variables, click Add New, set the name as PIXABAY_API_KEY, paste your key as the value, and select Production and Preview environments. For local development, create or update your .env.local file with PIXABAY_API_KEY=your_key. After saving in Vercel, trigger a new deployment from the Deployments tab (or push a small code change to trigger auto-deploy). The Pixabay API has rate limits of 100 requests per minute and 5,000 requests per hour for free accounts. These limits are generous for a personal or small-team tool, but if you expect high traffic you should implement response caching (as shown in the API route above).
1# .env.local (do NOT commit — add to .gitignore)2PIXABAY_API_KEY=your_pixabay_api_key_herePro tip: Pixabay's Terms of Service require that you display the photographer's name and a link back to their Pixabay profile page whenever you display their images. The API response includes a pageURL field with the direct link to the Pixabay page for each image.
Expected result: The PIXABAY_API_KEY variable appears in Vercel project settings. After the next deployment, /api/pixabay?q=mountains returns real Pixabay search results with image URLs, photographer info, and view counts.
Connect the Gallery Component and Handle Image Domains
Connect the Gallery Component and Handle Image Domains
Update your V0-generated gallery component to fetch from /api/pixabay and render the returned image data. The key challenge with Pixabay images in Next.js is configuring the allowed image domains in next.config.js. Pixabay serves images from cdn.pixabay.com — you need to add this hostname to the Next.js Image component's allowed domains. Without this, you will see 'Invalid src prop' errors when using the Next.js Image component with Pixabay URLs. The alternative is using standard img tags (which do not have domain restrictions), but Next.js Image is strongly recommended for performance. The component should also add proper attribution links as required by Pixabay's terms — show the photographer's name with a link to the pageURL field returned by the API. For complex gallery layouts or attribution management in multi-user tools, RapidDev's team can help build the full implementation.
Update the image gallery component to render real data from /api/pixabay. Map the hits array from the response: use webformatURL for the image src, user for the photographer name, pageURL for the attribution link, tags for the alt text, and totalHits for calculating total pages. Show a 'Photos by {user} on Pixabay' credit beneath each image card. Disable the Next Page button when (page * per_page) >= totalHits.
Paste this in V0 chat
1// next.config.js — allow Pixabay CDN images2/** @type {import('next').NextConfig} */3const nextConfig = {4 images: {5 remotePatterns: [6 {7 protocol: 'https',8 hostname: 'cdn.pixabay.com',9 },10 {11 protocol: 'https',12 hostname: 'pixabay.com',13 },14 ],15 },16};1718module.exports = nextConfig;Pro tip: Pixabay provides three image sizes: previewURL (150px thumbnail), webformatURL (medium, ~640px wide), and largeImageURL (full resolution). Use webformatURL for gallery grids and largeImageURL only when the user explicitly clicks to view full size.
Expected result: The live gallery shows real Pixabay images when you type a search query. Images load correctly through the Next.js Image component, and photographer attribution links appear under each photo. Pagination navigates through pages of results.
Common use cases
In-App Stock Image Picker
Embed a Pixabay image search modal inside a content editor or blog post builder so users can find and insert free stock photos without leaving your app. The modal shows a search field, a grid of results, and a click-to-select action.
Create a modal dialog with a search input at the top, a masonry grid of image thumbnails below, and a pagination bar at the bottom. Each image shows a hover overlay with photographer credit and a Select button. The modal has a close button in the top right. Fetch images from /api/pixabay?q={searchTerm}&page={page}.
Copy this prompt to try it in V0
Creative Asset Library Page
Build a standalone page where team members can search Pixabay for inspiration or download assets for marketing materials. Include category filters and image type toggles (photos, illustrations, vectors) to help narrow down results quickly.
Build an image library page with a prominent search bar, filter chips for category (Nature, Business, Technology, Food, Travel), and radio buttons for image type (Photos, Illustrations, Vectors, All). Show results in a responsive grid with 3 columns on desktop. Each card shows the image, view count, and a download link. Fetch from /api/pixabay.
Copy this prompt to try it in V0
Blog Featured Image Selector
Add a sidebar panel to a blog writing interface where authors can search Pixabay and set a featured image for their post in one click. The panel shows the current featured image and lets authors replace it by searching for something new.
Design a sidebar component (320px wide) for selecting a blog featured image. At the top show the current selected image with an X to clear it. Below show a search field and a 2-column grid of Pixabay thumbnails. Clicking a thumbnail sets it as the featured image and highlights it with a blue ring. Fetch from /api/pixabay?q={query}.
Copy this prompt to try it in V0
Troubleshooting
Error: 'Invalid src prop (https://cdn.pixabay.com/...)' in Next.js Image component
Cause: Next.js Image component blocks external image domains not listed in next.config.js remotePatterns. Pixabay serves images from cdn.pixabay.com.
Solution: Add cdn.pixabay.com to the remotePatterns in next.config.js as shown in Step 4. Commit the change and redeploy. Alternatively, temporarily use a plain img tag to unblock yourself while you fix the config.
1// next.config.js2const nextConfig = {3 images: {4 remotePatterns: [5 { protocol: 'https', hostname: 'cdn.pixabay.com' },6 ],7 },8};API returns { error: 'Pixabay API key not configured' } on Vercel but works locally
Cause: PIXABAY_API_KEY was added to .env.local for local development but not to Vercel Environment Variables.
Solution: Open Vercel Dashboard → your project → Settings → Environment Variables. Add PIXABAY_API_KEY with your key value and select Production and Preview environments. Then go to Deployments and trigger a redeploy — environment variable changes do not apply to existing deployments.
Search returns 0 results or hits array is empty for common search terms
Cause: The q parameter may be URL-encoded incorrectly, safesearch may be filtering results, or the search term does not match Pixabay's English-language index.
Solution: Check that the search query is being passed correctly to the API route. Verify the q parameter in your fetch URL is encoded with encodeURIComponent(). Try searching with simple single-word English terms to confirm the API is working, then test more complex queries.
1// Correct: encode the query parameter2const res = await fetch(`/api/pixabay?q=${encodeURIComponent(searchTerm)}&page=${page}`);Pagination shows a Next button after the last page of results
Cause: Pixabay caps totalHits at 500 results maximum. Your pagination logic may not account for this limit and shows a Next button when currentPage * perPage < totalHits, even when Pixabay has no more results to return.
Solution: Cap your pagination at 500 total results. Disable the Next Page button when (currentPage * perPage) >= Math.min(data.totalHits, 500).
1const maxResults = Math.min(data.totalHits, 500);2const hasNextPage = (currentPage * perPage) < maxResults;Best practices
- Always proxy Pixabay API calls through a Next.js API route to keep your API key server-side — even though the Pixabay API uses a query parameter for auth, exposing it in browser requests lets anyone steal your key and use your quota.
- Add caching to your API route's responses with Cache-Control headers. Pixabay search results for the same query rarely change minute to minute, so a 5-minute cache dramatically reduces API calls.
- Display photographer attribution (name + link to Pixabay page) next to every image you display from Pixabay. This is required by Pixabay's API Terms of Use and gives proper credit to creators.
- Use the previewURL (150px) for lazy-loaded thumbnail grids, webformatURL (640px) for displayed images, and largeImageURL only when users explicitly request full resolution — this saves bandwidth and speeds up page load.
- Implement debouncing on the search input so API calls only fire 300-500ms after the user stops typing, rather than on every keystroke. This reduces unnecessary API requests and improves the user experience.
- Add the safesearch=true parameter in all Pixabay API requests from your app unless you have a specific reason not to. This filters out adult content and is required for public-facing applications.
- Respect Pixabay's rate limits of 100 requests per minute. If your app has many concurrent users, implement server-side caching (e.g., with Vercel KV) to serve cached results without hitting Pixabay on every unique search.
Alternatives
Frequently asked questions
Is the Pixabay API free to use?
Yes, the Pixabay API is free for personal and commercial use. You need to register for a free Pixabay account and agree to their API Terms of Use. There is no paid tier — the free API provides access to over 4 million images and videos with a rate limit of 100 requests per minute.
Do I need to credit Pixabay photographers when using images in my V0 app?
Pixabay's license does not legally require attribution, but their API Terms of Use ask developers to display the photographer's name with a link to the Pixabay image page. Including attribution is a good practice that respects creators and keeps your app in compliance with Pixabay's developer terms.
Can I use Pixabay images commercially in my app?
Yes. Pixabay images are released under the Pixabay License, which allows free use for commercial purposes without attribution required (though appreciated). However, you cannot sell the images themselves or claim copyright over them. Read the full Pixabay License at pixabay.com/service/license-summary/ for details.
What is the difference between Pixabay API and Getty Images API?
Pixabay offers free royalty-free images with no per-download cost, making it ideal for tools where users need casual stock imagery. Getty Images API provides premium licensed photography from professional photographers, requires a paid agreement, and charges per licensed download. For most V0 app integrations, Pixabay is the more practical starting point.
How many images can I return per search request with the Pixabay API?
The Pixabay API allows up to 200 results per page with the per_page parameter. However, the total accessible results per query are capped at 500 hits (regardless of how many total matches exist). For galleries, a per_page of 20 or 30 with pagination provides the best user experience.
Can I search for videos as well as images with the Pixabay API?
Yes. The Pixabay API has a separate videos endpoint at pixabay.com/api/videos/ that works with the same API key and similar parameters. The response format is similar, with fields like videos.tiny.url, videos.small.url, and videos.medium.url for different resolution video sources.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your project.
Book a free consultation