@rironib/adsense
v1.0.0
Published
A lightweight, type-safe Google AdSense component for React and Next.js applications.
Maintainers
Readme
@rironib/adsense
A lightweight, type-safe, and optimized Google AdSense integration for React and Next.js (App Router).
🚀 Features
- Next.js Optimized: Built specifically for the Next.js App Router using
next/script. - Provider Pattern: Set your Publisher ID once at the root and use
<Ads />anywhere. - Environment Support: Automatically detects
NEXT_PUBLIC_ADSENSE_PUBLISHER_ID. - Auto-Initialization: Manages
adsbygoogle.push({})automatically. - Type-Safe: Full TypeScript support for all AdSense data attributes.
- Auto Ads Support: Enabling the provider is enough to support Auto Ads.
📦 Installation
npm install @rironib/adsense
# or
yarn add @rironib/adsense
# or
pnpm add @rironib/adsense🛠️ Setup
1. Environment Variable (Recommended)
Add your Publisher ID to your .env.local file:
NEXT_PUBLIC_ADSENSE_PUBLISHER_ID=ca-pub-22740176213607372. Add the Provider
Wrap your application in the root layout (app/layout.tsx).
import { AdSenseProvider } from "@rironib/adsense";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{/* pId is optional if NEXT_PUBLIC_ADSENSE_PUBLISHER_ID is set */}
<AdSenseProvider>{children}</AdSenseProvider>
</body>
</html>
);
}📖 Usage
Display Ads
Convert your standard AdSense snippet into a clean React component.
Standard Snippet:
<ins
class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-2274017621360737"
data-ad-slot="6292120180"
data-ad-format="auto"
data-full-width-responsive="true"
></ins>React Component:
import { Ads } from "@rironib/adsense";
const Sidebar = () => (
<Ads
slot="6292120180"
style={{ display: "block" }}
format="auto"
responsive={true}
/>
);In-Feed & In-Article Ads
Pass specific attributes like layoutKey or layout as props.
<Ads
slot="6292120180"
format="fluid"
layoutKey="-gw-e+1f-3d-2z"
style={{ display: "block" }}
/>⚙️ API Reference
AdSenseProvider
| Prop | Type | Default | Description |
| ---------- | ----------- | ---------------- | --------------------------------- |
| pId | string | process.env... | Your Google AdSense Publisher ID. |
| children | ReactNode | - | Your application content. |
Ads
| Prop | Type | Default | Description |
| ------------ | ------------------- | ---------------------- | ----------------------------------------------- |
| slot | string | Required | The ad unit ID from your dashboard. |
| format | string | 'auto' | Ad format ('auto', 'fluid', 'rectangle'). |
| responsive | boolean \| string | 'true' | Enable/Disable responsive layout. |
| layout | string | - | Used for specific ad types (e.g., In-article). |
| layoutKey | string | - | Used for In-feed ads. |
| style | CSSProperties | { display: 'block' } | Container styles. |
| className | string | - | CSS class for the ins element. |
📝 License
MIT © rironib
