nextjs

T.I.L.

Next.js 14 Metadata Best Practices

Learned about proper metadata handling in Next.js 14 client and server components

Next.js 14 Metadata Best Practices

Today I learned about the proper way to handle metadata in Next.js 14, especially with the new app router.

Key Points

  1. Metadata can't be exported from client components (those with 'use client' directive)
  2. Best practice is to create a separate metadata file
  3. Use layout.tsx for applying metadata to entire sections
  4. Can be static or dynamic using generateMetadata

Example Code

// metadata.ts
export const metadata = {
  title: 'My Page',
  description: 'Page description'
}
 
// layout.tsx
import { metadata as pageMetadata } from './metadata'
export const metadata = pageMetadata

This approach keeps the concerns separated and follows Next.js best practices for SEO optimization.

Tailwind CSS Dark Mode with Next.js

Discovered an elegant way to implement dark mode using Tailwind CSS and Next.js

Tailwind CSS Dark Mode with Next.js

Today I learned how to implement a clean dark mode solution using Tailwind CSS in a Next.js application.

Implementation Steps

  1. Configure Tailwind:
// tailwind.config.js
module.exports = {
  darkMode: 'class',
  // ...
}
  1. Add dark mode toggle:
const [darkMode, setDarkMode] = useState(false)
 
useEffect(() => {
  document.documentElement.classList.toggle('dark', darkMode)
}, [darkMode])
  1. Use in components:
<div className="bg-white text-black dark:bg-neutral-900 dark:text-white">
  Content
</div>

Key Takeaways

  • Use 'class' strategy for more control
  • Persist preference in localStorage
  • Add transition classes for smooth switching
  • Consider using next-themes package for SSR support

This approach provides a seamless dark mode experience with minimal configuration.