npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@cbrl/next

v0.5.2

Published

Next.js 16 building blocks: security headers with a reporting CSP, commit SHA, dev origins, health and CSP-report route handlers, safeNext, error/not-found pages, redacted Vercel Web Analytics.

Downloads

3,894

Readme

@cbrl/next

Building blocks every Next.js 16 app here repeats, in one place:

  • @cbrl/next/config (Node-only, for next.config.ts): a shared CSP baseline, the security header set with CSP reporting that actually reports, the build commit SHA and the dev origins allowlist.
  • @cbrl/next/server (Route Handlers): an uncached /api/health and a CSP report endpoint that strips personal data from reported URLs.
  • @cbrl/next/pages (Client Components): ErrorPage, NotFoundPage, GlobalError.
  • @cbrl/next/analytics (Client Component): WebAnalytics, cookieless Vercel Web Analytics that strips query/fragment and redacts private ids from URLs.
  • @cbrl/next (isomorphic, safe in Client Components): safeNext, the open-redirect guard for ?next= params.
pnpm add @cbrl/next

Peer dependency: next ^16.

next.config.ts

import { commitSha, cspDirectives, devOrigins, withSecurityHeaders } from '@cbrl/next/config'
import type { NextConfig } from 'next'

const supabaseOrigin = process.env.NEXT_PUBLIC_SUPABASE_URL
  ? new URL(process.env.NEXT_PUBLIC_SUPABASE_URL).origin
  : 'https://*.supabase.co'

const nextConfig: NextConfig = {
  typedRoutes: true,
  // Served by /api/health so a smoke test can check which commit is live.
  env: { NEXT_PUBLIC_COMMIT_SHA: commitSha() },
  // 127.0.0.1, <hostname>.local and the machine's LAN IPv4s.
  allowedDevOrigins: devOrigins(),
}

export default withSecurityHeaders(nextConfig, {
  csp: cspDirectives({
    'connect-src': [supabaseOrigin],
    'form-action': ['https://checkout.stripe.com'],
  }),
  cspMode: 'report-only',
  reportPath: '/api/csp-report',
})

withSecurityHeaders sets poweredByHeader: false and prepends one rule (source: '/:path*' by default) to whatever headers() the config already has, so an app rule for the same header key on a narrower path still wins.

The CSP baseline

cspDirectives(additions) starts from:

default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';
img-src 'self' data: https: blob:; font-src 'self' data:; connect-src 'self';
worker-src 'self' blob:; frame-src 'none'; frame-ancestors 'none'; object-src 'none';
base-uri 'self'; form-action 'self'

Additions are appended to the directive of the same name (keys are the CSP directive names). Adding to a directive whose baseline is 'none', such as frame-src, replaces the 'none'. Unknown directives are added as given, with an empty list emitting a bare directive ('upgrade-insecure-requests': []). buildCsp(directives) serializes any directive map if you need the string.

Headers

securityHeaders({ csp, cspMode, reportPath }) returns:

| Header | Value | | ----------------------------------------------------------------- | --------------------------------------------------------------- | | Strict-Transport-Security | max-age=31536000; includeSubDomains; preload | | X-Content-Type-Options | nosniff | | X-Frame-Options | DENY | | Referrer-Policy | strict-origin-when-cross-origin | | Permissions-Policy | camera=(), microphone=(), geolocation=(), interest-cohort=() | | Content-Security-Policy-Report-Only / Content-Security-Policy | the CSP, plus report-uri <reportPath>; report-to csp-endpoint | | Reporting-Endpoints (only with reportPath) | csp-endpoint="<reportPath>" |

A report-only CSP without reportPath blocks nothing and reports nothing; it is only useful in the browser console. Always pass reportPath. Both report-uri (Firefox, Safari) and report-to (Chromium) are emitted.

Route Handlers

// app/api/health/route.ts
import { healthRoute } from '@cbrl/next/server'

import { pool } from '@/lib/db'

export const GET = healthRoute({
  ping: () => pool.query('SELECT 1'),
  timeoutMs: 4000,
  onError: (error) => logger.error({ err: error }, 'health ping failed'),
})

Responds { status: 'ok' | 'error', commit, database: 'ok' | 'unreachable' } with 200 or 503. commit is NEXT_PUBLIC_COMMIT_SHA, else VERCEL_GIT_COMMIT_SHA, else null. The handler awaits connection(), so it is never prerendered with Cache Components, and sends Cache-Control: no-store. A ping that hangs longer than timeoutMs counts as unreachable.

// app/api/csp-report/route.ts
import { cspReportRoute } from '@cbrl/next/server'

export const POST = cspReportRoute({
  onReport: (violation) => logger.warn(violation, 'csp violation'),
})

Accepts application/csp-report (report-uri), application/reports+json (report-to) and application/json; anything else gets 415. Bodies over maxBytes (64 KiB by default) get 413, invalid JSON 400, otherwise 204. Each violation reaches onReport as:

interface CspViolation {
  documentUri: string // origin + path
  blockedUri: string // origin + path, a scheme such as `data`, or `inline` / `eval`
  violatedDirective: string
  disposition: 'enforce' | 'report'
  sourceFile?: string
  lineNumber?: number
  columnNumber?: number
}

Query strings and fragments are stripped from every URI and the referrer, script sample and user agent are dropped: URLs routinely carry tokens, emails and search terms, and violation logs must not become a store of personal data (LGPD). The endpoint is public by design (browsers send reports without credentials), so make sure your proxy.ts does not require a session on it.

readBackend

Server-side reads (database, auth) that degrade the page instead of crashing it when the backend is unavailable:

import { readBackend } from '@cbrl/next/server'

const result = await readBackend(() => loadDashboard(scope), { label: 'dashboard' })
if (!result.ok) return <BackendUnavailable /> // e.g. a "Try again" state
return <Dashboard data={result.data} />

Returns { ok: true, data } or { ok: false }. A read that throws, rejects or takes longer than timeoutMs (4000 by default, BACKEND_READ_TIMEOUT_MS) counts as unavailable and is logged with @cbrl/log as backend read unavailable ({ read: label, err }; pass logger to use another). The label names the read; never put personal data in it. A timed-out read is abandoned, not cancelled.

safeNext

import { safeNext } from '@cbrl/next'

redirect(safeNext(searchParams.get('next'), '/dashboard'))
const next = safeNext(raw, null) // string | null

Returns raw only when it is a same-origin path: starts with /, not // or /\, no control characters (browsers strip tabs and newlines, turning /\t/evil.com into //evil.com). Otherwise returns fallback. isSafeInternalPath(raw) is the underlying type guard.

Error and not-found pages

@cbrl/next/pages (Client Component entry; optional peers @cbrl/design, lucide-react, react) — pt-BR defaults, every string overridable:

// app/error.tsx
'use client'
import { ErrorPage } from '@cbrl/next/pages'
export default function Error({ reset }: { reset: () => void }) {
  return (
    <ErrorPage
      reset={reset}
      homeHref="/"
      homeLabel="Voltar ao início"
      retryLabel="Tentar de novo"
    />
  )
}

// app/not-found.tsx
import { NotFoundPage } from '@cbrl/next/pages'
export default function NotFound() {
  return <NotFoundPage homeHref="/" homeLabel="Voltar ao início" />
}

// app/global-error.tsx — replaces the root layout: import the global CSS here
;('use client')
import './globals.css'
import { GlobalError } from '@cbrl/next/pages'
export default GlobalError

Web Analytics

@cbrl/next/analytics (Client Component entry; optional peer @vercel/analytics). <Analytics /> with a beforeSend that never lets the query string or fragment leave the browser (OAuth codes, tokens, filters) and replaces the private ids of the listed routes by their placeholder. First match wins, so list static siblings before the dynamic rule. Unparseable URLs drop the event.

// app/layout.tsx
import { WebAnalytics } from '@cbrl/next/analytics'

;<WebAnalytics redactRoutes={['/orders/new', '/orders/[id]', '/invites/[orgId]/[inviteId]']} />
// /orders/42/edit?tab=x → /orders/[id]/edit

beforeSend runs after the redaction with the redacted event (return null to drop it). redactAnalyticsUrl(url, routes) and createAnalyticsBeforeSend(routes, hook) are exported for tests and custom wiring.

Rolling out an enforced CSP

  1. Ship cspMode: 'report-only' with reportPath and the cspReportRoute endpoint.
  2. Watch the reports through real traffic for a while (include auth, checkout and any third-party flows). For each legitimate violation, add the source to cspDirectives(...); ignore noise from browser extensions (chrome-extension, moz-extension blocked URIs).
  3. When the reports have run clean, switch to cspMode: 'enforce' and keep reportPath, so regressions keep being reported after they start being blocked.