All authors

Claude Skills by HoangNguyen0403
github.com/HoangNguyen04031,434 skills30 installs1,975 views
- Nextjs I18nMove user-visible text into translation dictionaries, for example `messages/en.json` and `messages/es.json`, and replace JSX literals with translation keys. Use `next-intl` for the App Router, load dictionaries server-side, and pass only the needed translated values to Client Components. Add locale middleware and an `app/[lang]` route segment, then verify that every translated route has consistent locale URLs and SEO metadata.Votes: 0GitHub stars: 549
- Nextjs I18nChoose one canonical locale URL shape, preferably `/en/about` and `/fr/about`, and migrate every page to it. Use `middleware.ts` for detection and redirects, `app/[lang]/` for App Router locale segments, and one consistent locale source of truth. Update links and canonical/`hreflang` metadata so shared links resolve predictably; do not mix locale prefixes and suffixes across routes.Votes: 0GitHub stars: 549
- Nextjs OptimizationUse `next/image` for the hero and reserve its layout space with explicit dimensions or `fill` inside a positioned, sized container. Mark the above-the-fold hero as the priority/LCP image, serve an appropriately sized responsive source, and provide an accurate `sizes` value. Measure LCP and CLS with DevTools or Speed Insights; do not use a bare `<img>` without dimensions.Votes: 0GitHub stars: 549
- Nextjs OptimizationReplace the Google Fonts `<link>` with `next/font`, preferably a self-hosted or package font, and apply the generated class from the layout. `next/font` handles loading and font-display behavior without a third-party head link, reducing layout shift and flashes of unstyled text. Verify CLS and font loading in the browser after the change.Votes: 0GitHub stars: 549
- Nextjs OptimizationExport static metadata for fixed page values or `generateMetadata` when metadata depends on route/data: ```ts export const metadata = { title: 'Products', description: 'Browse our products', openGraph: { title: 'Products', images: ['/og/products.png'] }, } ``` Keep metadata in `layout.tsx`/`page.tsx` or `generateMetadata`, not `_document.tsx`. Add canonical and locale metadata where applicable, and ensure each page has a meaningful title, description, and Open Graph image.Votes: 0GitHub stars: 549
- Nextjs Pages RouterIn `pages/`, export `getServerSideProps` as a standalone async function and return serializable props: ```tsx export async function getServerSideProps() { const posts = await postService.list() return { props: { posts } } } ``` Use `InferGetServerSidePropsType` for the page props. Call the service or database directly; do not fetch the app’s own API route from `getServerSideProps`.Votes: 0GitHub stars: 549
- Nextjs Pages RouterPages Router pages must not be async React components. Move request-time data fetching into `getServerSideProps` and pass the result as serializable props, or use `getStaticProps` for build-time data. Keep the default page component synchronous and use `useRouter()` from `next/router` for client navigation. Do not apply App Router Server Component patterns such as async page components or `'use client'`.Votes: 0GitHub stars: 549
- Nextjs Pages RouterExport `getStaticProps` for build-time data and `getStaticPaths` for dynamic pages. Use `fallback: 'blocking'` or `true` when new paths may be generated after the build, and set `revalidate` for ISR when content changes periodically. Return only serializable props, import services directly instead of fetching your own API route, and verify the generated paths and revalidation behavior with a production build.Votes: 0GitHub stars: 549
- Nextjs Pages RouterCreate `pages/[id].tsx` and read the route parameter in `getServerSideProps` or `getStaticProps`: ```tsx export async function getServerSideProps({ params }) { const item = await getItem(String(params?.id)) if (!item) return { notFound: true } return { props: { item } } } ``` Type the props with the appropriate Next.js helper. Use `[...slug].tsx` for catch-all segments and keep API endpoints under `pages/api/`.Votes: 0GitHub stars: 549
- Nextjs Pages RouterCreate `pages/_app.tsx` to wrap every Pages Router page: ```tsx import type { AppProps } from 'next/app' import '../styles/globals.css' export default function App({ Component, pageProps }: AppProps) { return <Component {...pageProps} /> } ``` Use `_app.tsx` for global CSS, providers, layouts, and global state. Keep custom document markup in `pages/_document.tsx`, and do not use App Router `app/` conventions in this project.Votes: 0GitHub stars: 549
- Nextjs Pages Router`'use client'` is an App Router directive and does not create a Server/Client Component boundary in the Pages Router. Pages Router pages are already rendered with the Pages Router model: use normal React components and client hooks such as `useState`, `useEffect`, and `useRouter()` as needed. Put server data fetching in `getServerSideProps` or `getStaticProps`; do not mix in App Router patterns.Votes: 0GitHub stars: 549
- Nextjs RenderingUse static generation (SSG) for the mostly immutable product listing. In the App Router, fetch with `force-cache` and use `generateStaticParams` for dynamic paths where applicable. If the catalog changes periodically, add ISR with `revalidate: N` or invalidate the owning tag/path after updates. This gives CDN-friendly HTML without paying the cost of SSR for every request.Votes: 0GitHub stars: 549
- Nextjs RenderingDo not await the three-second read at the root of the page. Split the dashboard into async components and wrap the slow section in `Suspense` with a skeleton; use `loading.tsx` for a route-level fallback. The static shell can stream immediately while the data-dependent island resolves. Choose `no-store` only if the data is truly request-time; otherwise use an appropriate cache or revalidation policy.Votes: 0GitHub stars: 549
- Nextjs RenderingDo not read `window.innerWidth` during the initial render. Keep the initial server and client output deterministic, then read it in a Client Component after mount: ```tsx 'use client' const [width, setWidth] = useState<number | null>(null) useEffect(() => setWidth(window.innerWidth), []) ``` Render the same placeholder until the effect runs, or use CSS media queries when the behavior is presentational. Avoid `typeof window` branches that produce different initial markup.Votes: 0GitHub stars: 549
- Nextjs SecurityTreat the action as an untrusted server entry point: authenticate, authorize ownership, validate the form input with Zod, and verify the request origin before deleting. Keep the action in an `actions.ts` server module, delegate the deletion to the DAL, and revalidate the exact post list/tag afterward. Never trust a hidden field or middleware alone for authorization.Votes: 0GitHub stars: 549
- Nextjs SecurityAvoid raw `innerHTML`; render text as escaped React content whenever possible. If trusted rich HTML is required, sanitize it with a well-maintained sanitizer such as DOMPurify before using `dangerouslySetInnerHTML`, and enforce a restrictive CSP. Store no secrets in the component, and treat the content as untrusted even if it came from an authenticated user.Votes: 0GitHub stars: 549
- Nextjs SecurityDo not expose a database password to a Client Component. Keep it in a server-only module and use it from a DAL, Server Action, or Route Handler. Only variables explicitly prefixed `NEXT_PUBLIC_` are intended for the browser, and a password must never receive that prefix. Add `import 'server-only'` to the module containing the secret and pass only safe DTOs to the client.Votes: 0GitHub stars: 549
- Nextjs Server ActionsDefine the mutation in an `actions.ts` module with `'use server'`, validate its input, authenticate/authorize inside the action, delegate storage to a DAL, and revalidate the affected tag or path: ```ts 'use server' export async function createPost(formData: FormData) { const title = String(formData.get('title') ?? '') if (!title.trim()) return { error: 'Title is required' } await requireUser() await posts.create({ title }) revalidatePath('/posts') } ``` Wire it with `<form action={createPost...Votes: 0GitHub stars: 549
- Nextjs Server ActionsUse Server Actions for mutations when the project uses the App Router; no custom API endpoint is required for a form in the same application. Put the action in `actions.ts`, validate `FormData`, authenticate and authorize inside it, call the DAL/service, then revalidate the owning tags or paths. Use a Route Handler instead when a public HTTP API or non-React client needs the boundary.Votes: 0GitHub stars: 549
- Nextjs Server Actions`useFormStatus` must run in a Client Component that is a descendant of the `<form>` using the action: ```tsx 'use client' import { useFormStatus } from 'react-dom' function SubmitButton() { const { pending } = useFormStatus() return <button disabled={pending}>{pending ? 'Saving…' : 'Save'}</button> } ``` Use `<form action={serverAction}>` and render `SubmitButton` inside it. Keep the action server-side and validate/authenticate it independently.Votes: 0GitHub stars: 549
- Nextjs Server ActionsParse `FormData` before touching storage or services, preferably with a Zod schema: ```ts const parsed = schema.safeParse({ title: formData.get('title') }) if (!parsed.success) return { error: 'Invalid title' } ``` Then authenticate and authorize the caller, call the DAL with `parsed.data`, and revalidate the exact tag/path changed by the mutation. Do not trust raw strings, hidden fields, or client-side validation as authorization.Votes: 0GitHub stars: 549
- Nextjs Server ActionsUse `useActionState` in a Client Component to bind a Server Action and expose its returned state: ```tsx const [state, formAction, pending] = useActionState(action, initialState) return <form action={formAction}>...</form> ``` The action should return a serializable success/error state, validate inputs, authenticate/authorize, and revalidate after success. Use `pending` for disabled controls; keep redirects and thrown errors in the action’s expected control flow rather than swallowing them.Votes: 0GitHub stars: 549
- Nextjs Server ActionsAfter authorization and a successful mutation, invalidate the affected data and call `redirect()`: ```ts await updatePost(input) revalidatePath(`/posts/${id}`) redirect(`/posts/${id}`) ``` `redirect()` throws a framework control-flow exception, so do not put it inside a `try/catch` that catches and suppresses it. Validate the input and perform auth inside the action before the mutation.Votes: 0GitHub stars: 549
- Nextjs Server ComponentsKeep `'use client'` out of the page/layout and place it at the smallest leaf that needs hooks or browser events. A page can fetch data as an async Server Component and pass serializable props to an interactive button, form, or chart Client Component. Do not move the whole tree to the client just to make one leaf interactive.Votes: 0GitHub stars: 549
- Nextjs Server ComponentsUse composition rather than importing a Server Component into a Client Component: ```tsx // Server component <ClientShell><ServerContent /></ClientShell> ``` `ClientShell` accepts `children` and renders it, while `ServerContent` performs server data access. Props crossing the boundary must be serializable; functions, class instances, and raw sensitive objects do not cross safely. A Client Component cannot directly import a Server Component.Votes: 0GitHub stars: 549
- Nextjs Server ComponentsYes—an async Server Component can call the database directly, preferably through a server-only DAL: ```tsx export default async function Page() { const user = await getUserDto() return <Profile user={user} /> } ``` Authenticate and authorize inside the DAL, return a minimal DTO, and never expose ORM instances or secrets to Client Components. Do not fetch the application’s own API route from the server; call the service directly.Votes: 0GitHub stars: 549
- Nextjs Server Components`useState` is a Client Component hook. Keep the component server-side if it only renders fetched data; move the interactive state into a small child with `'use client'` and pass it serializable initial data. For form or mutation feedback, use a Client Component with `useActionState`, `useFormStatus`, or `useOptimistic` while keeping the Server Action secure.Votes: 0GitHub stars: 549
- Nextjs Server ComponentsPut secrets and database logic in modules marked `import 'server-only'`, and keep those modules out of Client Component import graphs. Pass only minimal, serializable DTOs to client leaves; never pass raw database objects, tokens, or secret environment values. Use Server Actions or Route Handlers as explicit bridges for client-triggered operations and keep secret environment variables unprefixed by `NEXT_PUBLIC_`.Votes: 0GitHub stars: 549
- Nextjs Server ComponentsThe App Router renders Server Components on the server and sends HTML plus an RSC payload; only Client Components are hydrated with browser JavaScript. Hydration succeeds when the client’s initial output matches the server output. Avoid browser-only values such as `window`, `Date.now()`, or random values during initial render; read them in a Client Component effect or render a stable placeholder first. Use `Suspense`/`loading.tsx` for async loading states.Votes: 0GitHub stars: 549
- Nextjs State ManagementPut shareable filter state in URL search parameters using `useSearchParams` and `useRouter` (or server `searchParams` when filtering in a Server Component). Encode only the necessary primitives, update the URL with the desired history behavior, and derive the displayed results from those params. This makes links bookmarkable and shareable; do not use a global client store for state whose source of truth is the URL.Votes: 0GitHub stars: 549
- Nextjs State ManagementDo not mirror server data into `useState` and fetch it in `useEffect`. Fetch initial/server-owned data in a Server Component, or use SWR/TanStack Query when the client needs revalidation, polling, or optimistic updates. Keep `useState` for local UI state, and use a Client Component boundary only where interaction requires it.Votes: 0GitHub stars: 549
- Nextjs State Management`localStorage` is unavailable during Server Component rendering and reading it during the initial client render can produce different markup. Move the read into a `'use client'` component and perform it in `useEffect`, or gate the render behind a mounted flag so server and first client output match. Use URL state for shareable values and reserve a client store such as Zustand for complex UI state.Votes: 0GitHub stars: 549
- Nextjs StylingAssuming a Next.js App Router project using Tailwind CSS v4: ```bash npm install tailwindcss @tailwindcss/postcss postcss clsx tailwind-merge ``` Create `postcss.config.mjs`: ```js const config = { plugins: { "@tailwindcss/postcss": {}, }, }; export default config; ``` In `app/globals.css`: ```css @import "tailwindcss"; ``` Create `lib/utils.ts`: ```ts import { clsx, type ClassValue } from "clsx"; import { twMerge } from "tailwind-merge"; export function cn(...inputs: ClassValue[]) { return t...Votes: 0GitHub stars: 549
- Nextjs StylingMUI works with Next.js App Router, but it uses runtime CSS-in-JS and can force `'use client'` boundaries more widely. The preferred alternatives are Tailwind/shadcn or CSS Modules / SCSS because they are zero-runtime and RSC-compatible. If MUI is required: ```bash npm install @mui/material @emotion/react @emotion/styled @mui/material-nextjs ``` Create a client-only provider: ```tsx // app/providers.tsx 'use client'; import { AppRouterCacheProvider } from '@mui/material-nextjs/v15-appRouter'; ...Votes: 0GitHub stars: 549
- Nextjs StylingUse `next/image` and always provide `width` and `height`, or use the `fill` prop: ```tsx import Image from "next/image"; <Image src="/hero.jpg" alt="Hero" width={1200} height={675} /> ``` For a responsive container: ```tsx <div className="relative aspect-video"> <Image src="/hero.jpg" alt="Hero" fill className="object-cover" /> </div> ``` This reserves space before the image loads and prevents layout shift.Votes: 0GitHub stars: 549
- Nextjs TestingUse RTL with the project’s Jest/Vitest runner and `userEvent` to test behavior: 1. Render the login form with an MSW handler for the authentication request. 2. Locate fields and submit control with `getByRole`/`getByLabelText`. 3. `await user.type(...)` and `await user.click(...)`. 4. Assert the success message with `findByRole` or `findByText`. Reset handlers and mocks after each test; avoid testing implementation details or making real network calls.Votes: 0GitHub stars: 549
- Nextjs TestingMock the network boundary with MSW rather than allowing real `fetch` calls. Define shared request handlers for the success and failure responses, start the MSW server in the test setup, reset handlers after each test, and close it after the suite. Keep assertions focused on user-visible behavior and use `findByRole`/`waitFor` for async results. This makes CI deterministic and still exercises the request path.Votes: 0GitHub stars: 549
- Nextjs TestingUse Playwright for the full checkout journey: add a test that starts with an empty or prepared cart, navigates through checkout, fills customer/payment test data, submits, and asserts the order confirmation. Prefer accessible locators such as `getByRole`, isolate external payment calls with a test environment or route mock, and keep authentication/fixtures deterministic. Cover the critical flow without replacing unit tests for individual business rules.Votes: 0GitHub stars: 549
- Nextjs ToolingProfile the CI build first, then enable the appropriate tooling improvements: cache `.next/cache` keyed by lockfile and relevant build inputs, use Turbopack for supported development/incremental work, remove unused or heavy dependencies, and inspect bundle growth with `@next/bundle-analyzer`. Keep `next lint`/ESLint and `tsc` as CI gates, and compare build timings before and after each change rather than assuming a cache helps.Votes: 0GitHub stars: 549
- Nextjs ToolingConfigure `output: 'standalone'` in `next.config.js`, build the app, and copy the generated `.next/standalone` tree plus `.next/static` and `public` into a minimal production image. Install dependencies with a lockfile, run as a non-root user, expose only the needed port, and pass runtime configuration through the environment. Verify the image with `next start`/the standalone server and do not bake secrets into the image.Votes: 0GitHub stars: 549
- Nextjs ToolingKeep database passwords, signing keys, and other server-only values in environment variables without the `NEXT_PUBLIC_` prefix; validate them at runtime with a schema in a server-only module. Only intentionally public configuration gets `NEXT_PUBLIC_`, because it is bundled for the browser. Do not log secrets or pass them to Client Components, and verify the deployment environment supplies every required variable before starting.Votes: 0GitHub stars: 549
- Nextjs UpgradeUpgrade incrementally: inspect the current `next`, `react`, and `react-dom` versions, move 13 -> 14 -> 15, and keep peer versions compatible. Run the official codemods at each step, especially the async request API transform; await `params`, `searchParams`, `cookies()`, and `headers()`. Audit fetch caching for the v15 behavior, run `next dev` and `next build` after each major, and fix hydration/Turbopack errors before proceeding.Votes: 0GitHub stars: 549
- Nextjs UpgradeDo not assume the new cache behavior; audit every fetch and classify its freshness. Add `force-cache` or `next: { revalidate: N }` for data that should be cached, use `no-store` for request-specific data, and add `revalidateTag`/`revalidatePath` after mutations. Also check Router/Data/Full Route cache interactions, then verify the stale path with a production build and a mutation-to-refresh test.Votes: 0GitHub stars: 549
- Nextjs UpgradeDo not skip major versions. Follow an incremental path, 12 -> 13 -> 14 -> 15, using each version’s official migration guide and codemods, with compatible React/React DOM dependencies at each step. Run the app and build after every major, resolve breaking changes and async API migrations, and keep a record of manual fixes. Skipping makes it harder to attribute failures and can leave migrations unsupported.Votes: 0GitHub stars: 549
- Php Best PracticesFollow PSR-12 consistently: ~~~php <?php declare(strict_types=1); namespace App\Service; final class UserService { public function findById(int $id): ?User { return $this->repository->findById($id); } } ~~~ Use four spaces, same-line opening braces, one class per file, and place imports after the namespace. Use PHP CS Fixer with the PSR-12 preset to enforce the style.Votes: 0GitHub stars: 549
- Php Best PracticesApply SRP by keeping each class focused, and apply dependency inversion by depending on interfaces: ~~~php interface UserRepository { public function findById(int $id): ?User; } final class UserService { public function __construct( private UserRepository $repository, ) { } } ~~~ Use composition and constructor injection for testability; extract unrelated responsibilities instead of growing a large class.Votes: 0GitHub stars: 549
- Php Best PracticesSplit the God class by responsibility: put validation in a validator, persistence behind a repository interface, notifications behind a notifier interface, and orchestration in a small application service. Inject those interfaces through the constructor. Keep each class focused, use typed methods, and let the orchestrator coordinate collaborators rather than owning every implementation detail.Votes: 0GitHub stars: 549
- Php Best PracticesReturn early for invalid or exceptional cases so the happy path stays flat: ~~~php public function process(?User $user): Result { if ($user === null) { return Result::failure('User not found'); } if (!$user->isActive()) { return Result::failure('User is inactive'); } return $this->processor->process($user); } ~~~ Avoid an else after a return and keep nesting shallow.Votes: 0GitHub stars: 549
- Php Best PracticesUse a trait only for small, genuinely cross-cutting behavior: ~~~php trait HasTimestamps { private DateTimeImmutable $updatedAt; public function touch(): void { $this->updatedAt = new DateTimeImmutable(); } } final class User { use HasTimestamps; } ~~~ Keep traits focused and lightweight; do not use them to hide unrelated state or business responsibilities.Votes: 0GitHub stars: 549
- Php Best PracticesUse PascalCase for classes, camelCase for methods and variables, and SNAKE_CASE for class constants: ~~~php final class UserService { private const MAX_RETRIES = 3; public function getUserById(int $userId): ?User { // ... } } ~~~ Use descriptive names and avoid magic numbers or ambiguous abbreviations.Votes: 0GitHub stars: 549