w3resource

Build Modern Web Applications with Node.js and Next.js


Node.js with Next.js: Comprehensive Guide and Examples

Next.js is a React framework that enables server-side rendering (SSR), static site generation (SSG), and API routing. It is built on top of Node.js and provides a powerful toolkit for building modern web applications. Next.js simplifies React development with automatic optimization, page routing, and API endpoints. This guide explains how to set up Next.js with Node.js, key features, and practical examples.


Syntax:

To install Next.js, you need Node.js and npm (or yarn).

Create a Next.js App:

# Using npm
npx create-next-app@latest my-next-app

# Using yarn
yarn create next-app my-next-app

Steps to Set Up a Next.js Application

    1. Install Next.js: Use the create-next-app command to bootstrap a project.

    2. Run the Development Server: Use npm run dev or yarn dev.

    3. Create Pages: Add React components in the pages/ directory.

    4. Build the Project: Use npm run build or yarn build for production.

    5. Deploy: Deploy to platforms like Vercel, AWS, or your custom server.


Examples and Code

Below are step-by-step examples to demonstrate Next.js features:

1. Create a New Next.js Project

Run the following command to create a Next.js project:

Code:

# Create a new Next.js app
npx create-next-app@latest my-next-app

Output:

  • A new folder my-next-app will be created.
  • Pre-configured files like package.json, pages/, public/, and styles/.

2. Run the Development Server

Navigate into the project folder and start the server:

Code:

cd my-next-app
npm run dev

Output:

Visit http://localhost:3000 in your browser to see the default Next.js welcome page.


3. Create a Simple Page in Next.js

In Next.js, pages are created inside the pages/ directory. Each file corresponds to a route.

pages/index.js

Code:

// Import React to create components
import React from "react";

// Define a functional component for the home page
const HomePage = () => {
  return (
    <div>
      <h1>Welcome to My Next.js App!</h1>
      <p>This is the home page.</p>
    </div>
  );
};

// Export the component
export default HomePage;

Run:

npm run dev

Output:

Visit http://localhost:3000 to see:

Welcome to My Next.js App!
This is the home page.

4. Dynamic Routing in Next.js

Dynamic routes are created using square brackets [param].

Create a file pages/posts/[id].js:

Code:

import { useRouter } from "next/router";

const Post = () => {
  // Access the dynamic route parameter
  const router = useRouter();
  const { id } = router.query;

  return (
    <div>
      <h1>Post ID: {id}</h1>
      <p>This is a dynamic route example.>/p>
    </div>
  );
};
export default Post;

Run:

Visit http://localhost:3000/posts/123 and replace 123 with any ID.

Output:

Post ID: 123
This is a dynamic route example.

5. API Routes in Next.js

Next.js allows you to create API endpoints using the pages/api directory.

Create a file pages/api/hello.js:

Code:

// Export an API route handler function
export default function handler(req, res) {
  // Send a JSON response
  res.status(200).json({ message: "Hello from Next.js API!" });
}

Run:

Visit http://localhost:3000/api/hello.

Output:

{
  "message": "Hello from Next.js API!"
}


Key Features of Next.js

    1. File-Based Routing: Pages are created in the pages/ directory without additional configurations.

    2. Server-Side Rendering (SSR): Render pages on the server for better SEO and performance.

    3. Static Site Generation (SSG): Pre-render pages at build time.

    4. API Routes: Build API endpoints easily within pages/api/.

    5. Image Optimization: Use the next/image component for optimized images.

    6. Automatic Code Splitting: Load only the JavaScript needed for each page.


Next.js Deployment with Node.js

To deploy your Next.js project on a Node.js server:

    1. Build the Project:

    npm run build
    

    2. Start the Server:

    npm start
    

    3. Deploy: Use platforms like Vercel (native support), AWS, or custom Node.js servers.


Advantages of Using Next.js with Node.js

  • SEO-Friendly: With SSR and SSG, Next.js delivers better SEO results.
  • Fast Performance: Automatic code splitting and pre-rendering improve load times.
  • Easy Backend Integration: Next.js API routes allow backend logic within the same project.
  • Scalable: Can be deployed easily to cloud providers like Vercel, AWS, or Azure.


Follow us on Facebook and Twitter for latest update.