15 Exercise: Simple contact form in Next.js

15.1 Task

Create a simple Next.js application that contains a contact form with the fields “Name”, “Email” and “Message”. The form should send the entered data to an API route, which receives this data and outputs it in the console.

15.1.1 Requirements:

  1. create a Next.js component for the contact form.
  2. implement state management for the form fields
  3. add a submit function that sends the data to an API route (/api/contact)
  4. create the API route in Next.js that receives the sent data and outputs it to the server console.

15.2 Images and image optimization in Next.js

Image handling and optimization is a critical aspect of web application development to minimize load times and improve the user experience. Next.js provides powerful tools for optimizing images.

15.2.1 1. using the Next.js image components

Next.js provides a special <image /> component from the next/image module that is designed for optimizing and efficiently loading images. This component offers functions such as lazy loading, automatic scaling and the serving of modern image formats.

15.2.1.1 Example:

import Image from 'next/image';

function MyComponent() {
  return (
    <image
      src="/path/to/image.jpg"
      alt="description"
      width={500}
      height={300}
      layout="responsive"
    />
  );
}

15.2.2 2. image sizes and responsive images

With the layout attribute of the <image /> component, you can control the behavior of images with regard to responsiveness. The options fixed, intrinsic, responsive and fill offer various options for how the image should adapt to different screen sizes.

15.2.3 3. image formats and modern image loading

Next.js supports modern image formats such as WebP, which offers better compression while maintaining the same quality. If you provide images in WebP format, you can significantly reduce the file size.

15.2.4 4. placeholders and image loading

The placeholder attribute of the image component makes it possible to display a blurred image while the actual image is being loaded. This improves the perceived loading time and user experience.

15.2.5 5. server-side image optimization

Next.js offers the possibility to optimize images on the server side. With the Next.js Image Optimization API, images can be automatically optimized upon request. This reduces the need to manually edit images or save them in different sizes.

Image optimization in Next.js is a straightforward and effective affair thanks to the special <Image /> component and the integrated optimization functions. By using these tools, developers can improve the loading times of their applications and ensure a better user experience.