Rilasciato · in miglioramento
Guida a Next.js · 2/6
Per ora questo capitolo è disponibile solo in inglese.
Next.js uses file-system routing: folder and file names decide your URLs and how the UI is composed. Where you put a file is therefore part of your application's design. This chapter covers the top-level folders, configuration files, special file names and the conventions you will use every day.
A project created with create-next-app looks roughly like this (details depend on the options you chose):
my-app/
app/
layout.tsx root layout
page.tsx home page /
globals.css global styles
favicon.ico
public/ static files such as images
next.config.ts Next.js configuration
tsconfig.json TypeScript configuration
eslint.config.mjs lint configuration
package.json
next-env.d.ts generated type declarations| Folder or file | Purpose |
|---|---|
app | The App Router: routes, layouts and pages |
public | Static files served as-is. public/logo.png is available at /logo.png |
src | Optional. If chosen, app lives in src/app |
next.config.ts | Framework settings such as image domains, redirects and output mode |
.env* | Environment variable files |
proxy.ts | Code that runs before a request is handled. Earlier releases call this file middleware.ts |
Inside app, only files with reserved names have special meaning. Each folder (route segment) can contain:
| File | Meaning |
|---|---|
page.tsx | The UI for that URL. A route is public only when this file exists |
layout.tsx | Shared UI that wraps child routes and keeps its state across navigation |
loading.tsx | UI shown while content loads (a Suspense fallback) |
error.tsx | UI shown when a child throws (must be a Client Component) |
not-found.tsx | UI for notFound() calls and unknown URLs |
route.ts | A Route Handler that returns an HTTP response instead of UI |
template.tsx | Like a layout, but re-created on every navigation |
Because of this rule you can safely colocate components, styles and tests inside route folders: anything that is not page.tsx or route.ts is never exposed as a URL.
Square brackets in a folder name capture part of the URL as a parameter. In recent releases params is passed as a Promise, so you await it.
// app/blog/[slug]/page.tsx -> /blog/hello-world
export default async function PostPage({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const { slug } = await params;
return <h1>Post: {slug}</h1>;
}The folder naming conventions are:
[slug]: a single dynamic segment[...slug]: a catch-all segment that matches several levels (/docs/a/b/c)[[...slug]]: an optional catch-all that also matches the URL without parameters(marketing): a route group in parentheses. It does not appear in the URL and is used to split layouts or organize files_components: a private folder starting with an underscore, excluded from routing entirelyFramework configuration lives in next.config.ts (or .js, .mjs) at the project root. Writing it in TypeScript gives you autocompletion for every option.
// next.config.ts
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
images: {
remotePatterns: [{ protocol: "https", hostname: "images.example.com" }],
},
async redirects() {
return [{ source: "/old-blog/:slug", destination: "/blog/:slug", permanent: true }];
},
};
export default nextConfig;The paths setting in tsconfig.json maps @/ to the project root (or src), so you can write import { db } from "@/lib/db" instead of long relative paths. create-next-app configures this alias by default.
Environment variables are loaded from files such as .env, .env.local, .env.development and .env.production. Secrets usually go in .env.local, which should not be committed.
# .env.local
DATABASE_URL=postgres://user:pass@localhost:5432/app
NEXT_PUBLIC_SITE_NAME=My AppOnly variables whose names start with NEXT_PUBLIC_ are included in browser code. Everything else is readable on the server only, so never give that prefix to secrets such as database URLs or API keys.
The app directory also supports conventional files for search engines and social sharing. Dropping in favicon.ico, icon.png or opengraph-image.png generates the matching tags automatically, while robots.ts and sitemap.ts produce their content from code.
// app/sitemap.ts
import type { MetadataRoute } from "next";
export default function sitemap(): MetadataRoute.Sitemap {
return [
{ url: "https://example.com", lastModified: new Date() },
{ url: "https://example.com/about", lastModified: new Date() },
];
}app, and a route is public only when it has a page.tsx or route.ts.layout, loading, error and not-found divide up the UI responsibilities.[slug], (group) and _private handle dynamic URLs and organization.next.config.ts and secrets in .env.local, and prefix only browser-safe values with NEXT_PUBLIC_.
0 commenti
Accedi · Accedi per lasciare un commento.
Scrivi tu il primo commento.