y>

Next.js Tutorial

An Introduction to Next.js

What is Next.js?

Next.js is a React framework for building static and server-rendered applications.

Features of Next.js

  • Server-side Rendering (SSR)
  • Static Site Generation (SSG)
  • API Routes
  • File-system Routing
  • Built-in CSS and Sass Support
  • Image Optimization
  • Incremental Static Regeneration (ISR)
  • Environment Variables

Setting Up a Next.js Project

To create a new Next.js app, run:

npx create-next-app@latest

Project Structure

After creating a Next.js project, the basic structure includes: (Source)

  • app/ - App Router
  • pages/ - Pages Router
  • public/ - Static assets
  • src/ - Optional application source folder

Creating Pages

Create a new file in the app directory to add a new route:

// app/page.tsx
export default function Home() {
  return (
    

Welcome to Next.js!

) }

Linking Between Pages

Use the Link component from next/link to navigate between pages:

import Link from 'next/link';
export default function Home() {
  return (
    

Welcome to Next.js!

Go to About Page
) }

Styling in Next.js

Next.js supports various styling options:

  • CSS Modules
  • Global CSS
  • Styled JSX
  • CSS-in-JS libraries (e.g., styled-components)

CSS Modules

CSS Modules are supported by default. Create a CSS file and import it as a module:

// styles/Home.module.css
.container {
  padding: 20px;
}

// pages/index.js
import styles from '../styles/Home.module.css';

export default function Home() {
  return (
    

Welcome to Next.js!

) }

Global CSS

create file `app/global.css` and import in js file source

// app/global.css
body {
  padding: 20px 20px 60px;
  max-width: 680px;
  margin: 0 auto;
}

// pages/index.js
// These styles apply to every route in the application
import './global.css'

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    
      {children}
    
  )
}
                

API Routes

Next.js allows you to create API endpoints by adding files to the app/folderName/page.tsx directory to address api /folderName:

Server-side Rendering (SSR)

create interface

interface Post {
    userId: number;
    id: number;
    title: string;
    body: string;
}
                

fetch data

interface Post {
    userId: number;
    id: number;
    title: string;
    body: string;
}
const PostsPage = async () => {
const res = await fetch(
    'https://jsonplaceholder.typicode.com/posts'
);
const posts: Post[] = await res.json();
}
                

interface Post {
    userId: number;
    id: number;
    title: string;
    body: string;
}
const PostsPage = async () => {
const res = await fetch(
    'https://jsonplaceholder.typicode.com/posts'
);
const posts: Post[] = await res.json();
return (
<>
    

Users

Go Back To Index
    {posts.map(post =>
  • {post.title} link
  • )}
); }; export default PostsPage;

Dynamic Routes

Create dynamic routes by using brackets in the file name:

// app/users/[id]/page.tsx
'use client';
import React from 'react';
import {useParams} from "next/navigation";
import Link from "next/link";

interface User {
    id: number;
    name: string;
    username: string;
}

async function UserPage() {
    const params = useParams<{ id: string; }>()
    const res = await fetch(
        `https://jsonplaceholder.typicode.com/users/${params.id}`
    );
    const user: User = await res.json();
    return (
name: {user.name}
); } export default UserPage;

Image Optimization

Next.js provides a built-in component for image optimization: (Source)

import Image from 'next/image';

export default function Home() {
  return (
    

Welcome to Next.js!

Picture of the author
) }

Environment Variables

Use environment variables in Next.js by creating a .env.local file:

API_URL=https://api.example.com

Access them in your code via process.env:

export async function getStaticProps() {
  const res = await fetch(process.env.API_URL);
  const data = await res.json();

  return { props: { data } };
}

Deploying Next.js

You can deploy a Next.js app using Vercel, the platform from the creators of Next.js:

vercel

Or, deploy to other platforms like Netlify, AWS, and more.

Conclusion

Next.js provides a powerful way to build modern web applications with React.

Explore more in the official documentation.