Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Tailieu
https://github.com/hoangtannhut2209-glitch/tailieu
Admin
A repository containing various documents or learning materials.
Tokens:
6,338
Snippets:
23
Trust Score:
2.5
Update:
1 year ago
Context
Chat
Benchmark
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Next.js Configuration with next.config.js Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt Provides examples of configuring Next.js behavior using `next.config.js` or `next.config.ts`. Covers options like trailing slash, image optimization with remote patterns, redirects, and rewrites. ```typescript // next.config.ts import type { NextConfig } from "next"; const nextConfig: NextConfig = { /* config options here */ }; export default nextConfig; // next.config.js with advanced options /** @type {import('next').NextConfig} */ const nextConfig = { trailingSlash: true, images: { remotePatterns: [ { protocol: "http", hostname: process.env.NEXT_PUBLIC_WORDPRESS_API_HOSTNAME, port: "", }, ], }, }; module.exports = nextConfig; ``` -------------------------------- ### Next.js Link Component for Client-Side Navigation (TypeScript) Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt Illustrates how to use the `next/link` component for client-side navigation and data fetching with `useSwr`. This example fetches user data and renders a list of links, each navigating to a user-specific page. It includes basic loading and error state handling. ```typescript // pages/index.tsx import type { User } from "../interfaces"; import useSwr from "swr"; import Link from "next/link"; const fetcher = (url: string) => fetch(url).then((res) => res.json()); export default function Index() { const { data, error, isLoading } = useSwr<User[]>("/api/users", fetcher); if (error) return <div>Failed to load users</div>; if (isLoading) return <div>Loading...</div>; if (!data) return null; return ( <ul> {data.map((user) => ( <li key={user.id}> <Link href="/user/[id]" as={`/user/${user.id}`}> {user.name ?? `User ${user.id}`} </Link> </li> ))} </ul> ); } ``` -------------------------------- ### Next.js Form Component with Client-Side Navigation and Server Actions Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt Utilize the `next/form` component for enhanced form handling with automatic client-side navigation. This example demonstrates creating a new post, persisting it using Prisma, and then redirecting the user while maintaining client state. ```typescript // app/posts/new/page.tsx import Form from "next/form"; import prisma from "@/lib/prisma"; import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; export default function NewPost() { async function createPost(formData: FormData) { "use server"; const title = formData.get("title") as string; const content = formData.get("content") as string; const authorEmail = (formData.get("authorEmail") as string) || undefined; const postData = authorEmail ? { title, content, author: { connect: { email: authorEmail } }, } : { title, content }; await prisma.post.create({ data: postData }); revalidatePath("/posts"); redirect("/posts"); } return ( <Form action={createPost}> <input type="text" name="title" required placeholder="Title" /> <textarea name="content" placeholder="Content" /> <input type="text" name="authorEmail" placeholder="Author email" /> <button type="submit">Create Post</button> </Form> ); } ``` -------------------------------- ### Next.js Dynamic Routes with Static Generation Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt Implements dynamic routes for blog posts using Next.js's App Router. It leverages `generateStaticParams` to pre-render pages at build time based on slugs fetched from an API. The example includes metadata generation and fetching post content, with a dependency on local API functions like `getAllPosts` and `getPostBySlug`, and a `markdownToHtml` utility. ```typescript // app/posts/[slug]/page.tsx import { Metadata } from "next"; import { notFound } from "next/navigation"; import { getAllPosts, getPostBySlug } from "@/lib/api"; export default async function Post(props: Params) { const params = await props.params; const post = getPostBySlug(params.slug); if (!post) { return notFound(); } const content = await markdownToHtml(post.content || ""); return ( <main> <article className="mb-32"> <PostHeader title={post.title} coverImage={post.coverImage} date={post.date} author={post.author} /> <PostBody content={content} /> </article> </main> ); } type Params = { params: Promise<{ slug: string; }>; }; export async function generateMetadata(props: Params): Promise<Metadata> { const params = await props.params; const post = getPostBySlug(params.slug); if (!post) { return notFound(); } const title = `${post.title} | Next.js Blog Example`; return { title, openGraph: { title, images: [post.ogImage.url], }, }; } export async function generateStaticParams() { const posts = getAllPosts(); return posts.map((post) => ({ slug: post.slug, })); } ``` -------------------------------- ### Next.js App Router Basic Page and Layout Structure Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt Defines the basic structure for a page and layout component within the Next.js App Router. It uses file-system based routing where page.tsx and layout.tsx are special files that define UI components for specific routes. No external dependencies are required for this basic setup. ```typescript // app/page.tsx export default function Page() { return <h1>Hello, Next.js!</h1>; } // app/layout.tsx export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <body>{children}</body> </html> ); } ``` -------------------------------- ### Next.js API Routes - Pages Router Style Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt Implement traditional API routes in Next.js using the pages/api directory. These routes support various HTTP methods and can interact with data sources. The example shows fetching a list of users and handling GET/PUT requests for a specific user. ```typescript // pages/api/users.ts import type { NextApiRequest, NextApiResponse } from "next"; import type { User } from "../../interfaces"; const users: User[] = [{ id: 1 }, { id: 2 }, { id: 3 }]; export default function handler( _req: NextApiRequest, res: NextApiResponse<User[]>, ) { res.status(200).json(users); } ``` ```typescript // pages/api/user/[id].ts import type { NextApiRequest, NextApiResponse } from "next"; import type { User } from "../../../interfaces"; export default function userHandler( req: NextApiRequest, res: NextApiResponse<User>, ) { const { query, method } = req; const id = parseInt(query.id as string, 10); const name = query.name as string; switch (method) { case "GET": res.status(200).json({ id, name: `User ${id}` }); break; case "PUT": res.status(200).json({ id, name: name || `User ${id}` }); break; default: res.setHeader("Allow", ["GET", "PUT"]); res.status(405).end(`Method ${method} Not Allowed`); } } ``` -------------------------------- ### Pages Router Custom App Component Configuration (TypeScript) Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt Shows how to customize the default App component in the Next.js Pages Router using `_app.tsx`. This allows for global layouts, custom head tags, and importing global CSS. It includes examples of adding meta tags and preloading fonts. ```typescript // pages/_app.tsx import "nextra-theme-blog/style.css"; import type { AppProps } from "next/app"; import Head from "next/head"; import "../styles/main.css"; export default function App({ Component, pageProps }: AppProps) { return ( <> <Head> <link rel="alternate" type="application/rss+xml" title="RSS" href="/feed.xml" /> <link rel="preload" href="/fonts/Inter-roman.latin.var.woff2" as="font" type="font/woff2" crossOrigin="anonymous" /> </Head> <Component {...pageProps} /> </> ); } ``` -------------------------------- ### Next.js API Routes - Route Handlers Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt Shows how to create API endpoints using Route Handlers in Next.js App Router. The examples demonstrate a POST request to set a cookie and another POST request to revalidate cache tags, utilizing `NextResponse` and `revalidateTag` from 'next/server' and 'next/cache' respectively. A custom environment variable `CONTENTFUL_REVALIDATE_SECRET` is used for the revalidation endpoint. ```typescript // app/api/set-token/route.ts import { NextResponse } from 'next/server' export function POST() { const res = NextResponse.json({ message: 'successful' }) res.cookies.set('token', 'this is a token') return res } // app/api/revalidate/route.ts import { NextRequest, NextResponse } from "next/server"; import { revalidateTag } from "next/cache"; export async function POST(request: NextRequest) { const requestHeaders = new Headers(request.headers); const secret = requestHeaders.get("x-vercel-reval-key"); if (secret !== process.env.CONTENTFUL_REVALIDATE_SECRET) { return NextResponse.json({ message: "Invalid secret" }, { status: 401 }); } revalidateTag("posts"); return NextResponse.json({ revalidated: true, now: Date.now() }); } ``` -------------------------------- ### Server Actions for Todo Management with PostgreSQL Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt Demonstrates server actions for creating and deleting todos, interacting with a PostgreSQL database. It utilizes Next.js server actions, Zod for validation, and Next.js cache revalidation. It requires `next/cache`, `postgres`, and `zod`. ```typescript // app/actions.ts "use server"; import { revalidatePath } from "next/cache"; import postgres from "postgres"; import { z } from "zod"; let sql = postgres(process.env.DATABASE_URL || process.env.POSTGRES_URL!, { ssl: "allow", }); export async function createTodo( prevState: { message: string; }, formData: FormData, ) { const schema = z.object({ todo: z.string().min(1), }); const parse = schema.safeParse({ todo: formData.get("todo"), }); if (!parse.success) { return { message: "Failed to create todo" }; } const data = parse.data; try { await sql` INSERT INTO todos (text) VALUES (${data.todo}) `; revalidatePath("/"); return { message: `Added todo ${data.todo}` }; } catch (e) { return { message: "Failed to create todo" }; } } export async function deleteTodo( prevState: { message: string; }, formData: FormData, ) { const schema = z.object({ id: z.string().min(1), todo: z.string().min(1), }); const data = schema.parse({ id: formData.get("id"), todo: formData.get("todo"), }); try { await sql` DELETE FROM todos WHERE id = ${data.id}; `; revalidatePath("/"); return { message: `Deleted todo ${data.todo}` }; } catch (e) { return { message: "Failed to delete todo" }; } } ``` -------------------------------- ### Page Component to Display and Manage Todos Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt The main page component that fetches all todos from the database using `postgres` and renders them. It includes the `AddForm` and `DeleteForm` components. It requires `postgres`, `AddForm`, and `DeleteForm`. ```typescript // app/page.tsx import postgres from "postgres"; import { AddForm } from "@/app/add-form"; import { DeleteForm } from "@/app/delete-form"; let sql = postgres(process.env.DATABASE_URL || process.env.POSTGRES_URL!, { ssl: "allow", }); export default async function Home() { let todos = await sql`SELECT * FROM todos`; return ( <main> <h1 className="sr-only">Todos</h1> <AddForm /> <ul> {todos.map((todo) => ( <li key={todo.id}> {todo.text} <DeleteForm id={todo.id} todo={todo.text} /> </li> ))} </ul> </main> ); } ``` -------------------------------- ### Dynamic Component Import and Code Splitting in Next.js Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt Shows how to dynamically import components using `next/dynamic` for optimized bundle size and improved loading performance. Supports custom loading states and disabling Server-Side Rendering (SSR). ```typescript // app/page.tsx "use client"; import { useState } from "react"; import dynamic from "next/dynamic"; const DynamicComponent1 = dynamic(() => import("./_components/hello1")); const DynamicComponent2WithCustomLoading = dynamic( () => import("./_components/hello2"), { loading: () => <p>Loading caused by client page transition ...</p> }, ); const DynamicComponent3WithNoSSR = dynamic( () => import("./_components/hello3"), { loading: () => <p>Loading ...</p>, ssr: false }, ); const names = ["Tim", "Joe", "Bel", "Max", "Lee"]; export default function IndexPage() { const [showMore, setShowMore] = useState(false); const [results, setResults] = useState(); return ( <div> {/* Load immediately, but in a separate bundle */} <DynamicComponent1 /> {/* Show a progress indicator while loading */} <DynamicComponent2WithCustomLoading /> {/* Load only on the client side */} <DynamicComponent3WithNoSSR /> {/* Load on demand */} {showMore && <DynamicComponent5 />} <button onClick={() => setShowMore(!showMore)}>Toggle Show More</button> {/* Load library on demand */} <div style={{ marginTop: "1rem" }}> <input type="text" placeholder="Search" onChange={async (e) => { const { value } = e.currentTarget; // Dynamically load fuse.js const Fuse = (await import("fuse.js")).default; const fuse = new Fuse(names); setResults(fuse.search(value)); }} /> <pre>Results: {JSON.stringify(results, null, 2)}</pre> </div> </div> ); } ``` -------------------------------- ### App Router Loading, Error, and Not Found UI Components (TypeScript) Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt Demonstrates the use of special files `loading.tsx`, `error.tsx`, and `not-found.tsx` in the App Router for handling UI states. `loading.tsx` displays a loading indicator, `error.tsx` handles errors with a fallback UI and navigation, and `not-found.tsx` displays a message when a route is not found. ```typescript // app/loading.tsx import React from 'react' export default function OuterLoading() { return <div id="loading">Loading...</div> } // app/error.tsx 'use client' import Link from 'next/link' export default function ErrorComponent() { return ( <> <h1 id="error-component">Error Happened!</h1> <Link href="/result" id="to-result"> To Result </Link> </> ) } // app/not-found.tsx import styles from './style.module.css' export default function NotFound() { return ( <> <h1 id="not-found-component" className={styles.red}> Not Found! </h1> </> ) } ``` -------------------------------- ### Client Component Form for Adding Todos Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt A client component that uses `useActionState` and `useFormStatus` hooks from React to handle form submissions for creating todos. It calls the `createTodo` server action. It requires `react` and the `createTodo` server action. ```typescript // app/add-form.tsx "use client"; import { useActionState } from "react"; import { useFormStatus } from "react-dom"; import { createTodo } from "@/app/actions"; const initialState = { message: "", }; function SubmitButton() { const { pending } = useFormStatus(); return ( <button type="submit" aria-disabled={pending}> Add </button> ); } export function AddForm() { const [state, formAction] = useActionState(createTodo, initialState); return ( <form action={formAction}> <label htmlFor="todo">Enter Task</label> <input type="text" id="todo" name="todo" required /> <SubmitButton /> <p aria-live="polite" className="sr-only" role="status"> {state?.message} </p> </form> ); } ``` -------------------------------- ### Fetch API with Caching in Next.js Server Components Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt Demonstrates how to use the Fetch API with 'force-cache' option for optimized data fetching within Next.js Server Components. This method improves performance by caching fetched data. ```typescript // app/cases/fetch_cached/page.tsx export default async function Page() { await 1 return ( <> <p>This page renders two components each performing cached fetches.</p> <ComponentOne /> <ComponentTwo /> </> ) } async function ComponentOne() { return <div>message 1: {await fetchRandomCached('a')}</div> } async function ComponentTwo() { return ( <> <div>message 2: {await fetchRandomCached('b')}</div> <div>message 3: {await fetchRandomCached('c')}</div> </> ) } const fetchRandomCached = async (entropy: string) => { const response = await fetch( 'https://next-data-api-endpoint.vercel.app/api/random?b=' + entropy, { cache: 'force-cache' } ) return response.text() } ``` -------------------------------- ### Next.js Pages Router: getStaticProps and getStaticPaths for Dynamic Routes Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt Demonstrates how to use getStaticProps and getStaticPaths in Next.js Pages Router to generate static pages for dynamic routes. This allows for static site generation with dynamic URL segments and supports internationalization. ```typescript // pages/gsp/[slug].tsx import type { GetStaticProps, GetStaticPaths, InferGetStaticPropsType, } from "next"; import Link from "next/link"; import { useRouter } from "next/router"; import LocaleSwitcher from "../../components/locale-switcher"; type GspPageProps = InferGetStaticPropsType<typeof getStaticProps>; export default function GspPage(props: GspPageProps) { const router = useRouter(); const { defaultLocale, isFallback, query } = router; if (isFallback) { return "Loading..."; } return ( <div> <h1>getStaticProps page</h1> <p>Current slug: {query.slug}</p> <p>Current locale: {props.locale}</p> <p>Default locale: {defaultLocale}</p> <p>Configured locales: {JSON.stringify(props.locales)}</p> <LocaleSwitcher /> <Link href="/gsp">To getStaticProps page</Link> <br /> <Link href="/gssp">To getServerSideProps page</Link> <br /> <Link href="/">To index page</Link> <br /> </div> ); } type Props = { locale?: string; locales?: string[]; }; export const getStaticProps: GetStaticProps<Props> = async ({ locale, locales, }) => { return { props: { locale, locales, }, }; }; export const getStaticPaths: GetStaticPaths = ({ locales = [] }) => { const paths = []; for (const locale of locales) { paths.push({ params: { slug: "first" }, locale }); paths.push({ params: { slug: "second" }, locale }); } return { paths, fallback: true, }; }; ``` -------------------------------- ### Metadata Configuration with Metadata API in Next.js App Router Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt Illustrates how to define page metadata for SEO using the Metadata API within the Next.js App Router. This includes setting titles, descriptions, Open Graph images, and other head tags in the layout. ```typescript // app/layout.tsx import type { Metadata } from "next"; import { Inter } from "next/font/google"; import "./globals.css"; const inter = Inter({ subsets: ["latin"] }); export const metadata: Metadata = { title: `Next.js Blog Example`, description: `A statically generated blog example using Next.js.`, openGraph: { images: [HOME_OG_IMAGE_URL], }, }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <head> <link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png" /> <link rel="manifest" href="/favicon/site.webmanifest" /> <meta name="theme-color" content="#000" /> <link rel="alternate" type="application/rss+xml" href="/feed.xml" /> </head> <body className={inter.className}> <div className="min-h-screen">{children}</div> </body> </html> ); } ``` -------------------------------- ### Next.js Image Optimization: Internal and External Images Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt Utilizes the Next.js Image component for automatic image optimization, including lazy loading and responsive images. Demonstrates handling both internal images from the public directory and external images which require configuration in next.config.js. ```typescript // app/page.tsx import Image from "next/image"; import Link from "next/link"; import vercel from "../public/vercel.png"; const Index = () => ( <div> <h2 id="internal">Internal Image</h2> <p>The following is an example of a reference to an internal image from the public directory.</p> <Image alt="Vercel logo" src={vercel} width={1000} height={1000} style={{ maxWidth: "100%", height: "auto", }} /> <h2 id="external">External Image</h2> <p>External images must be configured in next.config.js using the remotePatterns property.</p> <Image alt="Next.js logo" src="https://assets.vercel.com/image/upload/v1538361091/repositories/next-js/next-js-bg.png" width={1200} height={400} style={{ maxWidth: "100%", height: "auto", }} /> </div> ); export default Index; // next.config.js /** @type {import('next').NextConfig} */ module.exports = { images: { remotePatterns: [ { protocol: "https", hostname: "assets.vercel.com", port: "", pathname: "/image/upload/**", search: "", }, ], }, }; ``` -------------------------------- ### Next.js Internationalization with App Router Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt Demonstrates internationalization (i18n) within the Next.js App Router using dynamic route segments. It utilizes `generateStaticParams` to create localized pages based on a predefined list of locales from `i18n-config.ts`. The layout dynamically sets the HTML language attribute. ```typescript // app/[lang]/layout.tsx import { i18n, type Locale } from "@/i18n-config"; export const metadata = { title: "i18n within app router - Vercel Examples", description: "How to do i18n in Next.js 16 within app router", }; export async function generateStaticParams() { return i18n.locales.map((locale) => ({ lang: locale })); } export default async function Root(props: { children: React.ReactNode; params: Promise<{ lang: Locale }>; }) { const params = await props.params; const { children } = props; return ( <html lang={params.lang}> <body>{children}</body> </html> ); } ``` -------------------------------- ### Locale Switcher using usePathname Hook Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt A client component that enables switching between different locales using the `usePathname` hook from Next.js navigation. It dynamically generates links based on the current path and available locales. It requires `next/navigation` and `next/link`. ```typescript // app/[lang]/components/locale-switcher.tsx "use client"; import { usePathname } from "next/navigation"; import Link from "next/link"; import { i18n, type Locale } from "@/i18n-config"; export default function LocaleSwitcher() { const pathname = usePathname(); const redirectedPathname = (locale: Locale) => { if (!pathname) return "/"; const segments = pathname.split("/"); segments[1] = locale; return segments.join("/"); }; return ( <div> <p>Locale switcher:</p> <ul> {i18n.locales.map((locale) => { return ( <li key={locale}> <Link href={redirectedPathname(locale)}>{locale}</Link> </li> ); })} </ul> </div> ); } ``` -------------------------------- ### Next.js Middleware for Request Manipulation Source: https://context7.com/hoangtannhut2209-glitch/tailieu/llms.txt Shows how to implement Next.js middleware to intercept requests before they are completed. This allows for rewriting URLs, redirecting, and adding custom headers based on request properties. ```typescript // middleware.js import { NextRequest, NextResponse } from 'next/server' export const config = { regions: 'auto', } export async function middleware(request) { const url = request.nextUrl // Rewrite root to a different page if (url.pathname === '/') { url.pathname = '/ssg/first' return NextResponse.rewrite(url) } // Redirect example if (url.pathname === '/redirect-to-somewhere') { url.pathname = '/somewhere' return NextResponse.redirect(url, { headers: { 'x-redirect-header': 'hi', }, }) } // Rewrite to dynamic route if (url.pathname === '/rewrite-to-dynamic') { url.pathname = '/blog/from-middleware' url.searchParams.set('some', 'middleware') return NextResponse.rewrite(url) } // Add custom headers return NextResponse.next({ headers: { 'req-url-pathname': request.nextUrl.pathname, 'req-url-query': request.nextUrl.searchParams.get('foo'), }, }) } ```