Tag: Module 8: Advanced Concepts

  • Module 8: Advanced Concepts

    Lesson 1: Image Optimization

    Next.js provides built-in support for image optimization, enabling faster load times and better performance.

          • How It Works:
            • Use the <Image /> component from next/image to serve optimized images.
            • Example:
          • import Image from ‘next/image’;

            export default function Home() {
            return <Image src=”/example.jpg” alt=”Example” width={500} height={500} />;
            }

            • Automatically adjusts image size based on the device’s screen size and resolution.
        • Features:
          • Lazy loading by default.
          • Automatic format conversion (e.g., JPEG to WebP).
          • Built-in caching for optimized delivery.
      • Best Practices:
        • Use the quality prop to balance image quality and size.
        • Leverage external image providers via next.config.js .

    Lesson 2: Middleware in Next.js

    Middleware in Next.js allows you to run custom code before a request is completed. It’s commonly used for authentication, logging, and request redirection.

      • How It Works:
        • Create a middleware file in the pages or middleware directory.
        • Example:

    export function middleware(req) { const url = req.nextUrl.clone();
    if (!req.headers.get(‘authorization’)) { url.pathname = ‘/login’;
    return NextResponse.redirect(url);
    }
    return NextResponse.next();
    }

    • Use Cases:
      • Redirect unauthorized users.
      • Add custom headers to requests.  Log user activities.
      •  Best Practices:
        • Test middleware locally to ensure accuracy.
        • Use middleware sparingly to avoid performance bottlenecks.

    Lesson 3: Internationalization (i18n)

    Next.js has built-in support for internationalization, allowing you to create multi-language applications effortlessly.

      • Setup:
        • Configure the i18n property in next.config.js :

    module.exports = { i18n: {
    locales: [‘en’, ‘fr’, ‘de’],
    defaultLocale: ‘en’,
    },
    };

      • Usage:
        • Access the current locale using useRouter :

    import { useRouter } from ‘next/router’;

    export default function Home() { const { locale } = useRouter();
    return <p>Current locale: {locale}</p>;
    }

      • Dynamic Translations:
        • Use libraries like next-i18next or react-intl for dynamic translation management.
    • Best Practices:
    • Store translation files in a structured directory.
    • Regularly review and update translations.

    Additional Resources

    Advanced Features