next-formatter
v2.3.0
Published
A universal formatter for numbers, currency, dates, and relative time — built for Next.js App Router, supporting server components, client components, and Node.js backends.
Maintainers
Keywords
Readme
next-formatter
A universal formatter for numbers, currency, dates, and relative time - built for Next.js App Router, supporting server components, client components, and Node.js backends.
Installation
Using your preferred package manager:
npm install next-formatter
# or
yarn add next-formatter
# or
pnpm add next-formatter
# or
bun add next-formatterRecommended Setup
Define your configuration once in a shared file to keep locale and currency consistent across server and client.
lib/formatter.ts
import { getFormatter as _getFormatter } from "next-formatter/server";
import type { NextFormatterConfig } from "next-formatter";
const config: NextFormatterConfig = {
locale: "en-US",
currency: "USD",
rules: {
compactThreshold: 10000,
},
};
export const formatterConfig = config;
export const getFormatter = () => _getFormatter(config);1. Add the Provider
Create a client wrapper component and add it to your root layout.
app/providers/formatter-provider.tsx
"use client";
import { FormatterProvider } from "next-formatter/client";
import { formatterConfig } from "@/lib/formatter";
import { ReactNode } from "react";
export function AppFormatterProvider({ children }: { children: ReactNode }) {
return (
<FormatterProvider config={formatterConfig}>
{children}
</FormatterProvider>
);
}app/layout.tsx
import { AppFormatterProvider } from "@/app/providers/formatter-provider";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<AppFormatterProvider>
{children}
</body>
</html>
);
}2. Server Components
import { getFormatter } from "@/lib/formatter";
export default async function Page() {
const fmt = await getFormatter();
return <h1>{fmt.currency(49.99)}</h1>;
}3. Client Components
"use client";
import { useFormatter } from "next-formatter/client";
export function Price({ value }) {
const { currency } = useFormatter();
return <span>{currency(value)}</span>;
}Dynamic Locale & Currency
Resolve locale and currency per request from session, cookies, or headers.
import type { NextFormatterConfig } from "next-formatter";
export const formatterConfig: NextFormatterConfig = {
getLocale: async () => {
const session = await auth();
return session?.user?.locale;
},
getCurrency: async () => {
const session = await auth();
return session?.user?.currency;
},
};Why next-formatter?
- Zero hydration mismatches — ICU spacing and fraction digits are normalized between server and client.
- Dynamic resolvers — detect locale and currency from cookies, headers, or your database per request.
- Tiny client bundle — server resolution means minimal JavaScript shipped to the browser.
- Drop-in — no global state, no providers required for server-only usage.
License
MIT © gauravgorade
