Product
Enterprise
Solutions
DocumentationPricing
Resources
Book a DemoSign InGet Started
Product
Solutions
Solutions
Blog |Treblle for Next.js

Treblle for Next.js

Other  |  Sep 25, 2025  |  5 min read  |  By Pratim Maloji Bhosale

Summarize with
Treblle for Next.js image

Pratim Bhosale is a Senior Developer Experience Engineer (Developer Advocate) at Treblle, specializing in full‑text, vector, and hybrid search. A recognized Google Developer Expert for Go, she speaks regularly at industry events, including WeAreDevelopers and JOTB, and participates in webinars on API design, governance, and integrating AI in search workflows. Before joining Treblle, Pratim worked as a full‑stack engineer at UBS and contributed to SurrealDB’s DevTools advocacy. Her work has earned industry recognition, including being named one of India’s top 91 engineers by the Economic Times and receiving the Kedar Tumne Innovation Award.

Next.js is one of the leading frameworks for building production-ready web applications that ship quickly. But teams still struggle to truly understand their APIs, how customers use them, and who those customers are. Top-level logging is not helpful when you need to understand the root cause of an API failure that requires tracing across multiple requests, or when customers report performance issues on a specific endpoint. This is where Treblle fits in, and we have made it easier for the Next.js developers and community to access API intelligence.

Today, we're excited to announce the official Treblle SDK for Next.js!

Until now, Treblle users have used the unified Node SDK to integrate Treblle in their Next.js apps.

The newly developed Treblle Next.js SDK supports the App Router, Pages Router, and Edge runtime.

Quick Setup

1. Install the SDK

npm install @treblle/next
# or
pnpm add @treblle/next
# or
yarn add @treblle/next

2. Get Your API Keys

  1. Set up your free account on Treblle.com

  2. Add your workspace details and select the Next.js integration when you add an API

Copy the keys to your .env.local file and follow the integration steps.

TREBLLE_SDK_TOKEN=your_sdk_token_here
TREBLLE_API_KEY=your_api_key_here


Important: Keep your keys server-side only. Never use NEXT_PUBLIC_* prefixes with Treblle credentials.

Integration Examples

For new Next.js projects using the App Router:

// app/api/users/route.ts
import {NextResponse } from 'next/server'
import { withTreblle } from '@treblle/next/integrations/nextjs'
 
const treblle =withTreblle({
sdkToken: process.env.TREBLLE_SDK_TOKEN!,
apiKey: process.env.TREBLLE_API_KEY!,
})
 
export const GET =treblle(async () => {
  // Your API logic here
  returnNextResponse.json({users: [] })
})
 
export const POST =treblle(async (request) => {
  const body = await request.json()
  // Create user logic
  returnNextResponse.json({success: true })
})
 

Pages Router

For existing projects using the Pages Router:

// pages/api/users.ts
import type {NextApiRequest,NextApiResponse } from 'next'
import { withTrebllePages } from '@treblle/next/integrations/nextjs'
 
const treblle =withTrebllePages({
sdkToken: process.env.TREBLLE_SDK_TOKEN!,
apiKey: process.env.TREBLLE_API_KEY!,
})
 
async functionhandler(req:NextApiRequest,res:NextApiResponse) {
  if (req.method === 'GET') {
    return res.status(200).json({users: [] })
  }
 
  if (req.method === 'POST') {
    // Create user logic
    return res.status(201).json({success: true })
  }
 
  return res.status(405).json({error: 'Method not allowed' })
}
 
export defaulttreblle(handler)
 

Global Middleware (Optional)

For broader visibility across all requests, you can add global middleware:

// middleware.ts
import {NextResponse } from 'next/server'
import { withTreblleMiddleware } from '@treblle/next/integrations/nextjs'
 
const treblle =withTreblleMiddleware({
sdkToken: process.env.TREBLLE_SDK_TOKEN!,
apiKey: process.env.TREBLLE_API_KEY!,
blocklistPaths: [/^\\/_next\\//, '/static', '/images'],
})
 
export defaulttreblle(async () =>NextResponse.next())
 
export const config = {
matcher: ['/api/:path*']  // Only monitor API routes
}
 

Note: Edge middleware has limitations with request body parsing. For complete monitoring, use the route handler wrappers shown above.

Configuration Options

Customize Treblle's behavior with these options:

const treblle =withTreblle({
sdkToken: process.env.TREBLLE_SDK_TOKEN!,
apiKey: process.env.TREBLLE_API_KEY!,
 
  // Additional fields to mask in logs (beyond defaults)
additionalFieldsToMask: ['customSecret', 'internalId'],
 
  // Paths to ignore completely
blocklistPaths: ['/api/health', /\\/api\\/internal\\/.*/],
 
  // Disable default static file filtering
ignoreDefaultBlockedPaths: false,
 
  // Enable debug logging
debug: process.env.NODE_ENV === 'development',
})
 

Production-Only Setup

Want to monitor only production traffic? Here's how:

import { withTreblle } from '@treblle/next/integrations/nextjs'
 
constcreateWrapper = () => {
  if (process.env.NODE_ENV === 'production') {
    returnwithTreblle({
sdkToken: process.env.TREBLLE_SDK_TOKEN!,
apiKey: process.env.TREBLLE_API_KEY!,
    })
  }
 
  // Return identity function in development
  return (handler: any) => handler
}
 
const treblle =createWrapper()
 
export const GET =treblle(async () => {
  returnNextResponse.json({message: 'Hello, world!' })
})
 

Edge Runtime Support

Both App Router handlers and middleware work seamlessly with the Edge runtime:

// app/api/edge-example/route.ts
export const runtime = 'edge'  // Enable Edge runtime
 
const treblle =withTreblle({
sdkToken: process.env.TREBLLE_SDK_TOKEN!,
apiKey: process.env.TREBLLE_API_KEY!,
})
 
export const GET =treblle(async () => {
  return newResponse(JSON.stringify({edge: true }), {
headers: { 'content-type': 'application/json' }
  })
})
 

Metadata tracking

All Treblle SDKs including the Next.js SDK automatically detect metadata like customer IDs, trace IDs, region etc.

All you have to do is add the right headers to your requests. The SDK will associate all API calls with the specified customer ID. No additional configuration is required.

What You'll See in Your Dashboard

Once integrated, your Treblle dashboard will show:

  • Request/Response logs with full payload details

  • Customers using your API ( including AI agents )

  • Performance metrics, including response times and error rates

  • API documentation generated automatically from your routes

  • Security alerts for suspicious patterns

  • Usage analytics to understand your API consumption

Troubleshooting

If you're not seeing data in your dashboard:

  1. Enable debug mode: Set debug: true in your configuration
  2. Verify credentials: Ensure your SDK Token and API Key match your dashboard
  3. Test a simple route: Create a basic GET endpoint to verify the integration
  4. Check blocklist: Make sure your routes aren't being filtered out

Security & Privacy

Treblle automatically masks sensitive data like authorization headers, password fields, credit card numbers, and common secret patterns

You can add custom fields to mask using the additionalFieldsToMask option.

Get Started Today

The Treblle Next.js SDK will make building and understanding the growth of your Next.js applications much faster and effortless. With just a few lines of code, you gain complete insight into your application's API layer.

Treblle SDKs are open-source, and we encourage/support contributions. Check out the new Next.js and let us know if you have any feedback or suggestions!

Resources:

Related Articles

API Security Isn’t Just Auth: Lessons from Real-World Breaches coverOther

API Security Isn’t Just Auth: Lessons from Real-World Breaches

On June 26, 2025, we hosted a webinar with API security expert Colin Domoney and Treblle’s Vedran Cindrić to unpack what really breaks API security. Here are the key takeaways, including real breach examples, common myths, and a practical security checklist.

Scaling API Governance: Lessons from the “Future Is Federated” Webinar coverOther

Scaling API Governance: Lessons from the “Future Is Federated” Webinar

Missed the webinar? Here are the top takeaways from “The Future Is Federated,” where Daniel Kocot, Vedran Cindrić, and Harsha Chelle shared practical strategies for scaling API governance in complex, fast-moving environments.

Understanding Your API Consumers: Why Knowing Your API’s Users Is Key to Success coverOther

Understanding Your API Consumers: Why Knowing Your API’s Users Is Key to Success

APIs aren’t just connectors, they’re products with real users. To succeed, teams must understand those users deeply. This article explores why consumer insight is the key to building better APIs and how leaders can turn that understanding into action.

© 2025 Treblle. All Rights Reserved.
GDPR BadgeSOC2 BadgeISO BadgeHIPAA Badge