DEV Community

Lay
Lay

Posted on

Everything you need to know about Next.JS to start a new application today

1. Introduction
2. The Project
3. Starting setup
4. Rounting
5. Project Routes
6. Navigating between pages
7. Conclusion

Everything you need to know about Next.JS to start a new application today.

1 Introduction

Today, we’ll dive into building an application with Next.js!

Next.js is a powerful React framework that goes beyond just front-end development. While React typically focuses on building user interfaces, Next.js enables full-stack applications by handling both the front end and back end in one unified framework. This approach is often referred to as a "Backend for Frontend" (BFF), allowing us to create complete, robust applications with ease.

Importants Links
Github Repository

2 The Project

The goal of this project is to create an event website dedicated to ticket sales. This platform will offer tickets for various types of events and will feature four main pages: the login page, an event feed, the purchase process, and the order summary page.

3 Starting setup

  1. Install Node.JS 18.8 or later.
  2. Creating project
npx create-next-app@latest
Enter fullscreen mode Exit fullscreen mode

Next this, will be show some questions for you:

This will be the name and folder name of your project.
What is your project named? eve

// **YES** - Use typescript is better, for this project, we will be use.
Would you like to use TypeScript? No / Yes

// **YES** - Eslint can help you to avoid errors
Would you like to use ESLint? No / Yes

// **NO** - For this project, we will use styled-components
Would you like to use Tailwind CSS? No / Yes

// **YES**
Would you like your code inside a `src/` directory? No / Yes

// **YES**
Would you like to use App Router? (recommended) No / Yes

// **NO**
Would you like to use Turbopack for `next dev`?  No / Yes

// **NO**
Would you like to customize the import alias (`@/*` by default)? No / Yes
What import alias would you like configured? @/*

Enter fullscreen mode Exit fullscreen mode
  1. Now you can run the command below to see the default Next.js page.
  npm run dev
Enter fullscreen mode Exit fullscreen mode

You can also use this approach, but it will build your application as static pages.

  npm run start
Enter fullscreen mode Exit fullscreen mode

4 Rounting

Next.js provides an easy way to handle routing in your application based on path names. Let’s take a closer look at each case.

1. Commom routing

  • In the /src/app directory, look for the page.tsx file. Every page file in Next.js is named this way, and you must always export it as the default. This is the default page displayed when you access ´http://localhost:3000´.

  • Now, let’s create a new route: inside the src/app directory, create a folder called auth. Within this folder, create a file named page.tsx. In this file, let’s add a simple div element with the text "login

export default function Auth() {
  return <div>login</div>;
}

Enter fullscreen mode Exit fullscreen mode

When you access "http://localhost:3000/auth" you need see only this:

Image description

2 - Grouping Routes

Sometimes we need to separate our code in more paths, but dont wanna change de url.

Change the 'auth' path to '(auth)' and create a path inside calls 'login' and move the last file to them.

Check two things:

  • the '/auth' url not working now, if you try access a 404 error will show you.
  • if you access '/login' you will see our component.

So this help us to create modules in the project without interfering with the user experience.

4 - Dynamic Routes

For a dynamic page, such as a product sales page, the layout should adapt to the product's specific information. In this case, details like the product name and price vary for each product.

We achieve this by using a product ID to fetch the relevant information, typically obtained from the URL.

To implement this, follow these steps:

  1. Inside /app, create a folder named events.
  2. Inside the events folder, create another folder named [id]—the brackets indicate a dynamic route for the product ID.
  3. Inside the [id] folder, create a file named page.tsx.

In page.tsx add this code:

'use client' //<- this is important, because whe are using a hook
//so we need to inform its a client side
import { useParams } from "next/navigation";

export default function EventInfo() {
    const params = useParams(); // get url params

    return <div>{params.id}</div>;
  }

Enter fullscreen mode Exit fullscreen mode

Now you can access '/events/111' and see this:

Image description

7 Project Routes

We already know the basics features to start our development, so let's get started intalling the dependencies.

npm i styled-components react-query 

Enter fullscreen mode Exit fullscreen mode

Creating authentication pages

Auth routes

Inside '(auth)' path create a "register", your path must looks likes this:

Image description

Platform routes

Inside 'app' path create a "platform"
Inside "platform" create "[id]"
Inside "platform" create "purchase"

Your path must looks likes this:

Image description

In this step you can create genericals pages, this articles is focus on nextjs features.

7 Project Routes - Middlewares

In our project, there are publics routers and privates routers, to protect and control the access, we need learn about middlewares.

Middlewares is a function that will be execute in every load page and to configure this:

  1. At 'src' path create middleware.ts
  2. Inside the file add this code.
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export default function middleware(request: NextRequest) {
  return NextResponse.redirect(new URL('/home', request.url))
}

Enter fullscreen mode Exit fullscreen mode
  1. Still inside this file, create 2 arrays
// Only authenticated access
const protectedRoutes = ["/platform"];

const publicRoutes = ["/login", "/register"];
Enter fullscreen mode Exit fullscreen mode
  1. Inside middleware function, we will verify the router rule and user session.
export function middleware(request: NextRequest) {
  // URL ACESSED
  const { pathname } = request.nextUrl;
  // USER SESSION
  const userId = request.cookies.get("user-id");

  // FUNCTION TO VERIFY IF IS A PROTECTED ROUTER
  const isPrivateRouter = protectedRoutes.some((path: string) =>
    pathname.startsWith(path)
  );

  if (isPrivateRouter && userId) {
    return NextResponse.next();
  }

  if (isPrivateRouter && !userId) {
    return NextResponse.redirect(new URL("/login", request.url));
  }

  // FUNCTION TO VERIFY IF IS A PUBLIC ROUTER
  const isPublicRouter = publicRoutes.some((path: string) =>
    pathname.startsWith(path)
  );

  if (isPublicRouter && !userId) {
    return NextResponse.next();
  }

  if (isPublicRouter && userId) {
    return NextResponse.redirect(new URL("/platform", request.url));
  }

  // REDIRECT TO LOGIN IF URL IS INVALID
  return NextResponse.redirect(new URL("/login", request.url));
}

Enter fullscreen mode Exit fullscreen mode

If you dont wanna execute the middleware in especifics routers, you can add in the same file this:

export const config = {
  matcher: ['/login'],
}
Enter fullscreen mode Exit fullscreen mode

7 Navigating between pages

In this step, disable the middleware.
Image description

To navigate between pages we must to use two ways.

When is a link options, the next component is the better instead the default html tag, because don't re rendering a page and causing a new pre render on server, and the Next Link component doesn't.

For example, create a button at login page for navigate to inside the platform.

Image description

When you click at button, you will see a re render page.

So let's try to use the next component.

Image description

Navigating like that, do you have a SPA (A SINGLE PAGE APPLICATION), that's made a better user experience.

Another way to do the same thing is using a router hook from next.

Image description

Conclusion

In this article, we explored key Next.js features, including the fundamentals of routing, creating dynamic and nested pages, organizing code with route groups, and implementing authentication and access control using middleware. Additionally, we learned how to optimize navigation for a better user experience by leveraging the Link component and programmatic routing with the useRouter hook. These concepts lay a strong foundation for building scalable and user-friendly applications with Next.js

Top comments (0)