Prebid.js Setup Guide: Implementing Header Bidding From Scratch
Prebid.js Setup Guide: Implementing Header Bidding From Scratch
Header bidding has become the standard for publishers who want to maximize their programmatic ad revenue. By allowing multiple demand sources to bid simultaneously on your inventory before your ad server makes a decision, header bidding creates genuine competition for every impression. Prebid.js is the most widely adopted open-source header bidding solution, used by thousands of publishers worldwide. This guide walks you through implementing Prebid.js from scratch, covering everything from initial setup to advanced optimization.
Whether you are migrating from a waterfall setup or implementing programmatic advertising for the first time, this guide provides the technical foundation you need. We cover each step in detail so you can implement with confidence, avoid common pitfalls, and start generating incremental revenue from day one.
Understanding How Prebid.js Works
Before writing any code, it is essential to understand the mechanics of header bidding with Prebid.js. In a traditional waterfall setup, your ad server calls demand sources sequentially, accepting the first bid that meets your floor price. This approach leaves money on the table because higher-paying demand sources later in the waterfall never get a chance to bid.
Prebid.js changes this by running an auction directly in the user's browser. When a page loads, Prebid.js simultaneously sends bid requests to all configured demand partners. These partners return their bids within a specified timeout period. Prebid.js then passes the winning bids as key-value pairs to your ad server, typically Google Ad Manager, which considers them alongside its own demand. The result is that every impression is sold to the highest bidder across all demand sources.
Key Components
- Prebid.js library: The core JavaScript library that orchestrates the auction process and manages communication between all components
- Bid adapters: Modules for each demand partner that translate Prebid requests into partner-specific API calls and normalize bid responses
- Ad units: Configuration objects that define your ad placements, sizes, and associated bidders with their specific parameters
- Ad server integration: Code that passes Prebid auction results to your ad server for final decisioning against other demand sources
- Analytics adapters: Optional modules for tracking auction performance, win rates, and revenue metrics across all demand partners
- Modules: Additional functionality like consent management, user ID resolution, price floors, and currency conversion
Step 1: Building Your Prebid.js Package
Prebid.js is modular, meaning you only include the bid adapters and features you need. This keeps the library size manageable and page load times fast. Visit the Prebid.js download page to build a custom package or use npm for integration into your build system.
Select the bid adapters for each demand partner you plan to work with. Common adapters include AppNexus (now Xandr), Rubicon Project (now Magnite), Index Exchange, OpenX, PubMatic, and Amazon TAM. Also include any analytics adapters you want, such as the Google Analytics adapter or Prebid Analytics. Be selective about which adapters you include, as each one adds to the library size and page weight.
Essential Modules to Include
- consentManagement: Required for GDPR and CCPA compliance, reads consent signals from your CMP and passes them to bidders
- priceFloors: Enables dynamic floor pricing for your inventory based on ad unit, media type, size, and other dimensions
- userId: Supports various identity solutions like Unified ID 2.0, LiveRamp, and ID5 for cookieless environments
- currency: Handles currency conversion if you work with international demand partners who bid in different currencies
- sizeMapping: Enables responsive ad units that adapt to different screen sizes and viewport widths
- gdprEnforcement: Automatically enforces consent requirements and filters bidders that lack proper consent
Download the built package or use npm to install Prebid.js in your build system. For production use, always use the minified version and serve it from your own domain or CDN to maintain control over the script. Self-hosting also eliminates the risk of third-party CDN outages affecting your ad revenue.
Step 2: Configuring Ad Units
Ad units are the core configuration objects that tell Prebid.js about your ad placements. Each ad unit defines a placement on your page, the sizes it accepts, and the bidders that should compete for it.
A well-configured ad unit includes a unique code that matches the div ID on your page where the ad will render, an array of accepted media types and sizes, and a list of bidders with their specific parameters. Each bidder requires different parameters, typically including a placement ID or site ID provided by the demand partner when you set up your account with them.
Responsive Ad Configuration
Use size mapping to define different ad sizes for different screen widths. This ensures that mobile users see appropriately sized ads while desktop users see larger, higher-paying formats. Define size mapping labels and apply them to your ad units so Prebid.js automatically selects the right sizes based on the user's viewport. For example, you might configure a leaderboard unit to serve 728x90 on desktop, 320x50 on mobile, and 468x60 on tablets.
Multi-Format Ad Units
Prebid.js supports multiple media types within a single ad unit, including banner, video, and native formats. Configuring multi-format ad units increases competition by allowing more bidders to participate, as some demand partners specialize in specific formats. A single ad placement can accept banner bids from display partners and native bids from native-focused partners, with the highest bid winning regardless of format.
Step 3: Setting Up the Prebid Auction
The auction configuration controls how Prebid.js runs its client-side auction. Key settings include the auction timeout, price granularity, and bid caching behavior.
Timeout Configuration
The timeout determines how long Prebid.js waits for bid responses before proceeding. A shorter timeout means faster page loads but potentially missed bids. A longer timeout captures more bids but delays ad rendering. Most publishers find that 1000 to 1500 milliseconds provides a good balance. Start with 1200 milliseconds and adjust based on your bidder response times and user experience metrics. Monitor timeout rates per bidder to identify partners that consistently respond slowly.
Price Granularity
Price granularity determines how bid prices are bucketed when passed to your ad server as key-value pairs. Prebid offers several preset options including low, medium, high, and dense granularity. Custom granularity gives you the most control, allowing you to define exactly how prices are bucketed at different ranges. Use finer granularity at lower price points where small differences matter and coarser granularity at higher prices where the incremental value of additional buckets diminishes.
Price Floors
Implement dynamic price floors to prevent selling your inventory below acceptable minimums. The Prebid price floors module supports floor rules based on ad unit, media type, ad size, and other dimensions. Start with conservative floors based on your historical CPM data and adjust upward as you gather more data about your inventory's true market value. Floors that are too aggressive will reduce fill rates, while floors that are too low will leave revenue on the table.
Step 4: Integrating with Google Ad Manager
Most publishers use Google Ad Manager (GAM) as their primary ad server. Integrating Prebid.js with GAM requires both JavaScript code on your page and line item configuration within GAM.
Page-Level Integration
After the Prebid auction completes, pass the winning bids to GAM as key-value pairs. Prebid.js provides helper functions that format bid data and set targeting on your GAM ad slots. The integration code should request bids from Prebid, set targeting on GAM slots when bids return, and then trigger the GAM ad request. Use the bidsBackHandler callback to coordinate timing between Prebid and GAM so that ad requests do not fire before bids are ready.
GAM Line Item Setup
Create line items in GAM that target the key-value pairs set by Prebid.js. You need line items at each price granularity bucket to ensure GAM can properly evaluate Prebid bids against its own demand. This typically requires creating hundreds of line items, one for each price point. Tools like Prebid Line Item Manager can automate this tedious but essential process.
Set each line item's CPM to match its targeted price bucket. Use the Prebid creative that calls the Prebid rendering function to display the winning bidder's ad. This creative is universal across all Prebid line items and handles rendering ads from any demand partner. Configure line items as price priority to ensure they compete fairly with other demand in your ad server.
Step 5: Testing and Debugging
Thorough testing is critical before launching header bidding in production. Prebid.js includes built-in debugging tools that help you verify your implementation.
Prebid Debug Mode
Enable debug mode by adding a query parameter to your page URL or setting the debug flag in your Prebid configuration. Debug mode outputs detailed logging to the browser console showing every step of the auction process, including bid requests sent, responses received, auction winners, and targeting values set on ad slots. Use this information to verify that all bidders are responding correctly and that winning bids are being properly communicated to your ad server.
Common Issues to Check
- Bid adapter errors: Verify that each bidder is returning valid bids by checking the console for adapter-specific error messages
- Timeout issues: Monitor which bidders consistently fail to respond within the timeout and consider increasing the timeout or removing slow bidders
- Size mismatches: Ensure that the sizes configured in your ad units match what your demand partners expect and what your page layout supports
- GAM targeting: Verify that key-value pairs are being correctly set on GAM ad slots using the GAM console or preview tools
- Creative rendering: Confirm that winning Prebid ads render correctly in their designated slots without layout issues or blank frames
- Consent flow: Test that the GDPR module properly reads consent strings and that bidders without consent are excluded from the auction
Step 6: Optimization and Monitoring
Once your Prebid.js implementation is live, continuous optimization is essential for maximizing revenue.
Bidder Performance Analysis
Monitor each bidder's win rate, average CPM, bid rate, and timeout rate. Remove underperforming bidders that rarely win or consistently time out, as they add latency without revenue benefit. Add new bidders strategically based on your traffic geography, content vertical, and available ad formats. Most publishers find that five to eight well-selected bidders per ad unit provides optimal competition without excessive latency.
A/B Testing
Test configuration changes systematically. Run A/B tests on timeout values, floor prices, bidder combinations, and ad unit configurations. Use server-side A/B testing where possible to avoid client-side bias. Measure not just revenue per session but also page load time and user engagement metrics to ensure optimization decisions consider the full picture.
Latency Optimization
Header bidding adds latency to your page load. Minimize this impact by loading Prebid.js asynchronously, using the fastest available CDN, implementing lazy loading for below-the-fold ad units, and limiting the number of bidders per ad unit to the most competitive partners. Consider server-side header bidding through Prebid Server for additional latency reduction, especially on mobile where network conditions are variable.
Prebid.js implementation is a significant technical undertaking, but the revenue gains are substantial. Publishers who switch from waterfall to header bidding typically see CPM increases of 20 to 50 percent. Take the time to implement correctly, test thoroughly, and optimize continuously. The effort compounds over time as you refine your bidder stack, floor pricing, and auction configuration to extract maximum value from every impression on your site.