Next.js-specific integration components and utilities for Chakra UI with server-side rendering support
npx @tessl/cli install tessl/npm-chakra-ui--next-js@2.4.0@chakra-ui/next-js provides Next.js-specific integration components and utilities for Chakra UI. It bridges the gap between Chakra UI's design system and Next.js framework features, ensuring optimal server-side rendering, emotion cache management, and seamless integration of Next.js optimized components with Chakra UI styling capabilities.
npm install @chakra-ui/next-js @chakra-ui/react @emotion/react next reactimport { CacheProvider, Image, Link } from "@chakra-ui/next-js";For specific entry points:
import { Image } from "@chakra-ui/next-js/image";
import { Link } from "@chakra-ui/next-js/link";
import { CacheProvider } from "@chakra-ui/next-js/emotion-cache-provider";
import { useEmotionCache } from "@chakra-ui/next-js/use-emotion-cache";
import { interopDefault } from "@chakra-ui/next-js/interop";For CommonJS:
const { CacheProvider, Image, Link } = require("@chakra-ui/next-js");import { ChakraProvider } from "@chakra-ui/react";
import { CacheProvider, Image, Link } from "@chakra-ui/next-js";
// App setup with cache provider (if needed for hydration issues)
function App({ children }: { children: React.ReactNode }) {
return (
<CacheProvider>
<ChakraProvider>{children}</ChakraProvider>
</CacheProvider>
);
}
// Using optimized components
function MyPage() {
return (
<div>
<Image
src="/hero.jpg"
alt="Hero image"
width={800}
height={400}
borderRadius="lg"
shadow="lg"
/>
<Link
href="/about"
color="blue.500"
_hover={{ color: "blue.600" }}
>
About Us
</Link>
</div>
);
}@chakra-ui/next-js is built around several key integration points:
useEmotionCache hook for proper SSR hydrationinteropDefault utility for handling default export compatibility between CommonJS and ES modulesEmotion cache provider component for resolving hydration issues in Next.js applications. Note: This component is deprecated and no longer necessary in current versions.
/**
* @deprecated - This component is no longer necessary
*/
function CacheProvider({ children }: CacheProviderProps): React.ReactElement;
/**
* @deprecated - This component type is no longer necessary
*/
interface CacheProviderProps extends PropsWithChildren<EmotionCacheOptions> {}Usage Example:
import { CacheProvider } from "@chakra-ui/next-js";
import { ChakraProvider } from "@chakra-ui/react";
// Only use if experiencing hydration issues
function Providers({ children }: { children: React.ReactNode }) {
return (
<CacheProvider>
<ChakraProvider>{children}</ChakraProvider>
</CacheProvider>
);
}Chakra UI styled wrapper around Next.js Image component, combining Next.js image optimizations with Chakra UI styling capabilities.
const Image: ChakraComponent<"img", NextImageProps>;
interface ImageProps extends NextImageProps, Omit<HTMLChakraProps<"img">, keyof NextImageProps> {}Key Next.js Image Props (forwarded):
src - Image source URLalt - Alternative text for accessibilitywidth, height - Dimensions for optimizationfill - Fill parent containersizes - Responsive sizes stringpriority - Load image with high priorityquality - Image quality (1-100)placeholder - Placeholder behavior ("blur" | "empty")blurDataURL - Data URL for blur placeholderloader - Custom image loader functionunoptimized - Disable Next.js optimizationloading - Loading behavior ("lazy" | "eager")crossOrigin - CORS setting for the imagedecoding - Image decoding hint ("async" | "auto" | "sync")referrerPolicy - Referrer policy for the image requestuseMap - Associates image with a client-side image maponLoadingComplete - Callback when image loading completesUsage Examples:
import { Image } from "@chakra-ui/next-js";
// Basic usage with Chakra styling
<Image
src="/hero.jpg"
alt="Hero image"
width={800}
height={400}
borderRadius="xl"
shadow="2xl"
_hover={{ transform: "scale(1.05)" }}
/>
// Responsive image with Next.js optimization
<Image
src="/responsive-image.jpg"
alt="Responsive image"
fill
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
objectFit="cover"
borderRadius={{ base: "md", lg: "lg" }}
/>
// Priority image with blur placeholder
<Image
src="/hero.jpg"
alt="Above the fold hero"
width={1200}
height={600}
priority
placeholder="blur"
blurDataURL="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ..."
bg="gray.100"
/>Chakra UI styled wrapper around Next.js Link component, combining Next.js routing optimizations with Chakra UI styling and theming.
const Link: LinkComponent;
interface LinkProps extends
Merge<
HTMLChakraProps<"a"> & ThemingProps<"Link"> & ChakraLinkProps,
Omit<NextLinkProps, LegacyProps>
> {}
type LinkComponent = FC<RefAttributes<HTMLAnchorElement> & LinkProps>;Key Next.js Link Props (forwarded):
href - Destination URL or pathreplace - Replace current history entryscroll - Scroll to top after navigationshallow - Update path without running data fetchingChakra UI Props:
isExternal - Open link in new tab (sets target="_blank")Usage Examples:
import { Link } from "@chakra-ui/next-js";
// Internal navigation with Chakra styling
<Link
href="/about"
color="blue.500"
fontWeight="semibold"
_hover={{ color: "blue.600", textDecoration: "underline" }}
>
About Us
</Link>
// External link
<Link
href="https://chakra-ui.com"
isExternal
color="teal.500"
_hover={{ color: "teal.600" }}
>
Visit Chakra UI
</Link>
// Styled with theme variants
<Link
href="/contact"
variant="ghost"
size="lg"
colorScheme="purple"
>
Contact
</Link>
// Complex routing with Next.js features
<Link
href={{
pathname: "/products/[id]",
query: { id: "123", category: "electronics" }
}}
replace
scroll={false}
color="gray.700"
_hover={{ bg: "gray.50" }}
p={2}
borderRadius="md"
>
Product Details
</Link>Internal utility function for handling default export compatibility between CommonJS and ES modules. Available from the interop entry point for advanced use cases.
/**
* Ensures compatibility between CommonJS and ES module default exports
* @param mod - Module that may or may not have a default export
* @returns The default export if available, otherwise the module itself
*/
function interopDefault<T>(mod: T): T;Usage Example:
import { interopDefault } from "@chakra-ui/next-js/interop";
import SomeModule from "some-module";
// Ensure we get the correct export regardless of module format
const SafeModule = interopDefault(SomeModule);React hook for creating and managing emotion cache with server-side rendering support in Next.js applications.
/**
* Creates and manages emotion cache for server-side rendering
* @param options - Optional emotion cache configuration
* @returns Emotion cache instance configured for Next.js SSR
*/
function useEmotionCache(options?: EmotionCacheOptions): EmotionCache;
interface EmotionCacheOptions extends Partial<CacheOptions> {}Usage Example:
import { useEmotionCache } from "@chakra-ui/next-js/use-emotion-cache";
import { CacheProvider as EmotionCacheProvider } from "@emotion/react";
import { ChakraProvider } from "@chakra-ui/react";
function MyApp({ Component, pageProps }: AppProps) {
const cache = useEmotionCache({
key: 'chakra',
prepend: true,
});
return (
<EmotionCacheProvider value={cache}>
<ChakraProvider>
<Component {...pageProps} />
</ChakraProvider>
</EmotionCacheProvider>
);
}// Core component prop types
interface CacheProviderProps extends PropsWithChildren<EmotionCacheOptions> {}
interface ImageProps extends NextImageProps, Omit<HTMLChakraProps<"img">, keyof NextImageProps> {}
interface LinkProps extends
Merge<
HTMLChakraProps<"a"> & ThemingProps<"Link"> & ChakraLinkProps,
Omit<NextLinkProps, LegacyProps>
> {}
// Emotion cache configuration
interface EmotionCacheOptions extends Partial<CacheOptions> {}
// Internal utility types
type Pretty<T> = { [K in keyof T]: T[K] } & {};
type Merge<P, T> = Pretty<Omit<P, keyof T> & T>;
type LegacyProps = "as" | "legacyBehavior" | "passHref";
type LinkComponent = FC<RefAttributes<HTMLAnchorElement> & LinkProps>;
// Re-exported from dependencies
interface NextImageProps {
src: string | StaticImageData;
alt: string;
width?: number;
height?: number;
fill?: boolean;
sizes?: string;
quality?: number;
priority?: boolean;
placeholder?: "blur" | "empty";
blurDataURL?: string;
loader?: ImageLoader;
unoptimized?: boolean;
loading?: "lazy" | "eager";
// ... additional Next.js Image props
}
interface NextLinkProps {
href: Url;
replace?: boolean;
scroll?: boolean;
shallow?: boolean;
// ... additional Next.js Link props
}The package provides multiple entry points for optimized imports:
@chakra-ui/next-js): All components and types@chakra-ui/next-js/image - Image component and types@chakra-ui/next-js/link - Link component and types@chakra-ui/next-js/emotion-cache-provider - CacheProvider (deprecated)@chakra-ui/next-js/use-emotion-cache - useEmotionCache hook@chakra-ui/next-js/interop - Internal utilitiesas, legacyBehavior, passHref) for cleaner APIApp Router Setup (Next.js 13+):
// app/providers.tsx
'use client';
import { ChakraProvider } from '@chakra-ui/react';
export function Providers({ children }: { children: React.ReactNode }) {
return <ChakraProvider>{children}</ChakraProvider>;
}
// app/layout.tsx
import { Providers } from './providers';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>
<Providers>{children}</Providers>
</body>
</html>
);
}Pages Router Setup (Next.js 12 and earlier):
// pages/_app.tsx
import { ChakraProvider } from '@chakra-ui/react';
import type { AppProps } from 'next/app';
function MyApp({ Component, pageProps }: AppProps) {
return (
<ChakraProvider>
<Component {...pageProps} />
</ChakraProvider>
);
}
export default MyApp;