{"id":18933846,"url":"https://github.com/mchamoudadev/nextjs-getting-started","last_synced_at":"2025-09-05T06:31:28.499Z","repository":{"id":198063677,"uuid":"699499113","full_name":"mchamoudadev/nextjs-getting-started","owner":"mchamoudadev","description":null,"archived":false,"fork":false,"pushed_at":"2023-10-31T13:29:54.000Z","size":189,"stargazers_count":2,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-06T00:11:11.899Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mchamoudadev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-10-02T18:52:01.000Z","updated_at":"2024-04-13T18:05:22.000Z","dependencies_parsed_at":"2023-10-04T07:45:06.484Z","dependency_job_id":"47ced805-10f8-4726-8fbc-26614b007047","html_url":"https://github.com/mchamoudadev/nextjs-getting-started","commit_stats":null,"previous_names":["mchamoudadev/nextjs-getting-started"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/mchamoudadev/nextjs-getting-started","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mchamoudadev%2Fnextjs-getting-started","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mchamoudadev%2Fnextjs-getting-started/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mchamoudadev%2Fnextjs-getting-started/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mchamoudadev%2Fnextjs-getting-started/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mchamoudadev","download_url":"https://codeload.github.com/mchamoudadev/nextjs-getting-started/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mchamoudadev%2Fnextjs-getting-started/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":273722702,"owners_count":25156300,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-05T02:00:09.113Z","response_time":402,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-08T11:56:38.079Z","updated_at":"2025-09-05T06:31:27.429Z","avatar_url":"https://github.com/mchamoudadev.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# NextJs The React Framework for the Web\n\n**What is NextJs ?**\n\nNext.js is a full-stack framework built on top of React. It facilitates building server-rendered and static web applications. With Next.js, you can create server-side routes and API endpoints, handle server-side rendering (SSR), static site generation (SSG), and client-side rendering (CSR). This framework streamlines the development process, ensuring optimal performance, SEO, and user experience. The recent enhancements in Next.js, like the App Router update, align with modern React features, making it a robust choice for full-stack development.\n\n\n# Exploring Rendering Methods in Next.js\n\n---\n\n## Server-Side Rendering (SSR)\n- **Introduction**: \n  - Generates HTML on the server per request.\n  - Sends a fully rendered page to the client.\n- **Advantages**:\n  - Ideal for SEO-critical pages.\n  - Great for dynamic content.\n- **Scenario**:\n  - A news website with constantly updating content.\n\n---\n\n## Static Site Generation (SSG)\n- **Introduction**:\n  - Generates HTML at build time.\n  - Reuses generated pages for each request.\n- **Advantages**:\n  - Fast load times.\n  - Suited for static content.\n- **Scenario**:\n  - A blog or documentation site.\n\n---\n\n## Client-Side Rendering (CSR)\n- **Introduction**:\n  - Renders pages in the browser using JavaScript.\n  - Initial load fetches a bare HTML file, then JS renders the content.\n- **Advantages**:\n  - Interactive UIs.\n  - Less server load.\n- **Scenario**:\n  - A dynamic and interactive application like a dashboard.\n\n---\n\n## Incremental Static Regeneration (ISR)\n- **Introduction**:\n  - Updates static pages incrementally after build.\n  - Combines benefits of SSR and SSG.\n- **Advantages**:\n  - Fresh content with optimized performance.\n  - Best of both SSR and SSG worlds.\n- **Scenario**:\n  - An e-commerce site with frequently changing product details.\n\n\n---\n\n## Building Full Stack Applications with Next.js\n\n- **Introduction**:\n  - Create both front-end and back-end in a single project.\n  - Server-side routes and API endpoints for back-end logic.\n- **Advantages**:\n  - Unified development experience.\n  - Streamlined deployment.\n- **Scenario**:\n  - Building a full-fledged e-commerce site with user authentication, product listings, and a checkout process, all managed within a single Next.js project.\n\n\n# Installation\n\n**System Requirements:**\n\n***Node.js 16.14*** or later.\nmacOS, Windows (including WSL), and Linux are supported.\n\n\n**Automatic Installation**\n\nWe recommend starting a new Next.js app using create-next-app, which sets up everything automatically for you. To create a project, run:\n\n```bash\nnpx create-next-app@latest\n```\n\nOn installation, you'll see the following prompts:\n\n```bash\nWhat is your project named? my-app\nWould you like to use TypeScript? No / Yes\nWould you like to use ESLint? No / Yes\nWould you like to use Tailwind CSS? No / Yes\nWould you like to use `src/` directory? No / Yes\nWould you like to use App Router? (recommended) No / Yes\nWould you like to customize the default import alias (@/*)? No / Yes\nWhat import alias would you like configured? @/*\n\n```\n\n### roadmap \n\n**File Structure**\nPractical Example\n\n**pages and routing**\nPractical Example\n\n\n**Client and Server Component**\n\nClient-side rendering (CSR) and server-side rendering (SSR) are distinct methods of rendering web pages, each with its own advantages and disadvantages::\n\n1. **Initial Load**: \n   - **CSR**: Delays in initial content rendering can frustrate users.\n   - **SSR**: Immediate rendering is user-friendly, especially on slow networks.\n   \n2. **SEO**:\n   - **CSR**: Search engine crawlers might struggle to index dynamic content.\n   - **SSR**: Fully-rendered pages are easily indexed, boosting SEO.\n\n3. **Security**:\n   - **CSR**: More client-side code could expose vulnerabilities.\n   - **SSR**: Limits client exposure, securing sensitive logic.\n\n4. **Real-time Updates**:\n   - **CSR**: Easier with frameworks like React for dynamic content updates.\n   - **SSR**: Requires additional configurations for real-time updates.\n\nEach scenario necessitates a trade-off, and your project's priorities will guide the rendering choice.\n\n\n### Data Fetching\n\nThe release of NextJS 13 brought about a plethora of new and impressive features, with one standout being the updated data fetching and management process. The fetch API replaced the more complicated functions, including getServerSideProps, getStaticProps, and getInitialProps.\n\n**fetch() API**\nReact recently introduces support for async/await in Server Components. You can now write Server Components using standard JavaScript await syntax by defining your component as an async function and that is what turned out to be a big plus point for NextJS 13.\n\n\n```js\nimport React from 'react';\n\nconst page = async () =\u003e {\n    const posts = await fetch('https://jsonplaceholder.typicode.com/posts');\n    const postData = await posts.json();\n\n    return (\n        \u003cdiv\u003e\n\n            \u003ch1\u003ePosts\u003c/h1\u003e\n            {postData.map(post =\u003e (\n                \u003ch1\u003e{post.title}\u003c/h1\u003e\n            ))}\n        \u003c/div\u003e\n    );\n};\nexport default page;\n```\nnote the fact that you no longer need to do this on the page level, like if you did before using getStaticProps or getServerSideProps. You can do this inside any component.\n\n**Client Components**\nFor now, if you need to fetch data in a Client Component, NextJS 13 recommends using a third-party library such as SWR or React Query.\n\n**Caching Data**\nCaching stores data so it doesn't need to be re-fetched from your data source on every request.\n\nBy default, Next.js automatically caches the returned values of fetch in the Data Cache on the server. This means that the data can be fetched at build time or request time, cached, and reused on each data request.\n\n```js\n// 'force-cache' is the default, and can be omitted\nfetch('https://...', { cache: 'force-cache' })\n\n```\n\n**Revalidating Data**\nRevalidation is the process of purging the Data Cache and re-fetching the latest data. This is useful when your data changes and you want to ensure you show the latest information.\n\nCached data can be revalidated in two ways:\n\n**Time-based revalidation:** Automatically revalidate data after a certain amount of time has passed. This is useful for data that changes infrequently and freshness is not as critical.\n**On-demand revalidation:** Manually revalidate data based on an event (e.g. form submission). On-demand revalidation can use a tag-based or path-based approach to revalidate groups of data at once. This is useful when you want to ensure the latest data is shown as soon as possible (e.g. when content from your headless CMS is updated).\n\n**Time-based Revalidation**\nTo revalidate data at a timed interval, you can use the next.revalidate option of fetch to set the cache lifetime of a resource (in seconds).\n\n```js\nfetch('https://...', { next: { revalidate: 3600 } })\n```\n\nAlternatively, to revalidate all fetch requests in a route segment, you can use the Segment Config Options.\n\n```js\nexport const revalidate = 3600 // revalidate at most every hour\n```\n\n\n### options.cache\n\nConfigure how the request should interact with Next.js Data Cache.\n\n```javascript\nfetch(`https://...`, { cache: 'force-cache' | 'no-store' })\n```\n\n- `force-cache` (default) - Next.js looks for a matching request in its Data Cache...\n- `no-store` - Next.js fetches the resource from the remote server...\n\n### options.next.revalidate\n\nSet the cache lifetime of a resource (in seconds).\n\n```javascript\nfetch(`https://...`, { next: { revalidate: false | 0 | number } })\n```\n\n- `false` - Cache the resource indefinitely...\n- `0` - Prevent the resource from being cached...\n- `number` - (in seconds) Specify the resource should have a cache lifetime...\n\n### options.next.tags\n\nSet the cache tags of a resource.\n\n```javascript\nfetch(`https://...`, { next: { tags: ['collection'] } })\n```\nData can then be revalidated on-demand using revalidateTag...\n\n\n**Static Data Fetching**\nfetch by default caches the data. So, even if the data from the API changes, when you refresh the page, the site doesn't update the data. This works great for sites which have static data which seldom changes. The example above demonstrates how to do this because it is the same as doing\n\n```js\nfetch(\"https://jsonplaceholder.typicode.com/posts\", {\n  cache: \"force-cache\",\n});\n\n```\n\n**Dynamic Data Fetching**\nYou can tell the fetch API to never cache the data by changing force-cache to no-cache or no-store(both signify the same in NextJS).\n\n```js\nfetch(\"https://jsonplaceholder.typicode.com/posts\", {\n  cache: \"no-cache\"\n});\n```\n\n#Routing In NextJs 13\n\n# Special File Names and Folder Naming Patterns in NextJs 13's app folder\n\n## Reserved file names in the app folder\n- `page.js`: Main entry point for each folder.\n- `layout.js`: Contains the wrapping layout for pages.\n- `template.js`: Similar to `layout.js` but remounts on navigation.\n- `head.js`: Used to customize the page head.\n- `error.js`: Used in data fetching to show intermediate states.\n- `not-found.js`: Renders the error screen for a not found item.\n\n## Special naming conventions for folders\n- `[id]`: Query parameters for routing.\n- `[...folder_name_here]`: Catch-all segments for varied URL mappings.\n- `(folder_name_here)`: Named route groups for organizing routes without affecting the URL.\n\n[Reference](https://www.js-craft.io/blog/next-13-special-files-and-folders-naming-conventions-in-the-app-folder/)\n\n---\n\n### Layouts\n\nA layout is UI that is shared between multiple pages. On navigation, layouts preserve state, remain interactive, and do not re-render. Layouts can also be nested.\n\nYou can define a layout by default exporting a React component from a layout.js file. The component should accept a children prop that will be populated with a child layout (if it exists) or a child page during rendering.\n\n\n\n```jsx\nexport default function RootLayout({\n  children,\n}) {\n  return (\n    \u003chtml lang=\"en\"\u003e\n      \u003cbody\u003e{children}\u003c/body\u003e\n    \u003c/html\u003e\n  )\n}\n```\n\n### Nesting Layouts\n\nLayouts defined inside a folder (e.g. app/dashboard/layout.js) apply to specific route segments (e.g. acme.com/dashboard) and render when those segments are active. By default, layouts in the file hierarchy are nested, which means they wrap child layouts via their children prop.\n\n\n```jsx\nexport default function DashboardLayout({\n  children,\n}) {\n  return \u003csection\u003e{children}\u003c/section\u003e\n}\n```\n\n### Loading UI and Streaming\n\nThe special file loading.js helps you create meaningful Loading UI with React Suspense. With this convention, you can show an instant loading state from the server while the content of a route segment loads. The new content is automatically swapped in once rendering is complete.\n\n\n### Instant Loading States\n\nAn instant loading state is fallback UI that is shown immediately upon navigation. You can pre-render loading indicators such as skeletons and spinners, or a small but meaningful part of future screens such as a cover photo, title, etc. This helps users understand the app is responding and provides a better user experience.\n\nCreate a loading state by adding a loading.js file inside a folder.\nIn the same folder, loading.js will be nested inside layout.js. It will automatically wrap the page.js file and any children below in a \u003cSuspense\u003e boundary.\n\n\n\n### Streaming with Suspense\nIn addition to loading.js, you can also manually create Suspense Boundaries for your own UI components. The App Router supports streaming with Suspense for both Node.js and Edge runtimes.\n\nWhat is Streaming?\nTo learn how Streaming works in React and Next.js, it's helpful to understand Server-Side Rendering (SSR) and its limitations.\n\nWith SSR, there's a series of steps that need to be completed before a user can see and interact with a page:\n\n1. First, all data for a given page is fetched on the server.\n2. The server then renders the HTML for the page.\n3. The HTML, CSS, and JavaScript for the page are sent to the client.\n4. A non-interactive user interface is shown using the generated HTML, and CSS.\n5. Finally, React hydrates the user interface to make it interactive.\n\nThese steps are sequential and blocking, meaning the server can only render the HTML for a page once all the data has been fetched. And, on the client, React can only hydrate the UI once the code for all components in the page has been downloaded.\n\nSSR with React and Next.js helps improve the perceived loading performance by showing a non-interactive page to the user as soon as possible.\n\nHowever, it can still be slow as all data fetching on server needs to be completed before the page can be shown to the user.\n\nStreaming allows you to break down the page's HTML into smaller chunks and progressively send those chunks from the server to the client.\n\n\nThis enables parts of the page to be displayed sooner, without waiting for all the data to load before any UI can be rendered.\n\nStreaming works well with React's component model because each component can be considered a chunk. Components that have higher priority (e.g. product information) or that don't rely on data can be sent first (e.g. layout), and React can start hydration earlier. Components that have lower priority (e.g. reviews, related products) can be sent in the same server request after their data has been fetched.\n\n\n\nStreaming is particularly beneficial when you want to prevent long data requests from blocking the page from rendering as it can reduce the Time To First Byte (TTFB) and First Contentful Paint (FCP). It also helps improve Time to Interactive (TTI), especially on slower devices.\n\n### Example\n\n\u003cSuspense\u003e works by wrapping a component that performs an asynchronous action (e.g. fetch data), showing fallback UI (e.g. skeleton, spinner) while it's happening, and then swapping in your component once the action completes.\n\n```jsx \n\nimport { Suspense } from 'react'\nimport { PostFeed, Weather } from './Components'\n \nexport default function Posts() {\n  return (\n    \u003csection\u003e\n      \u003cSuspense fallback={\u003cp\u003eLoading feed...\u003c/p\u003e}\u003e\n        \u003cPostFeed /\u003e\n      \u003c/Suspense\u003e\n      \u003cSuspense fallback={\u003cp\u003eLoading weather...\u003c/p\u003e}\u003e\n        \u003cWeather /\u003e\n      \u003c/Suspense\u003e\n    \u003c/section\u003e\n  )\n}\n```\n\n### not-found.js\n\nThe **not-found** file is used to render UI when the notFound function is thrown within a route segment. Along with serving a custom UI, Next.js will return a 200 HTTP status code for streamed responses, and 404 for non-streamed responses.\n\n```jsx\nimport Link from 'next/link'\n \nexport default function NotFound() {\n  return (\n    \u003cdiv\u003e\n      \u003ch2\u003eNot Found\u003c/h2\u003e\n      \u003cp\u003eCould not find requested resource\u003c/p\u003e\n      \u003cLink href=\"/\"\u003eReturn Home\u003c/Link\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n\n### Catch-all Segments in NextJs for E-Commerce URL Structure\n\nIn the context of an e-commerce platform, managing routes effectively becomes crucial to ensure a smooth user navigation experience. Utilizing NextJs's catch-all segments can be highly beneficial in crafting a flexible URL strategy to manage various product hierarchies and categories.\n\nConsider an e-commerce platform with various products, each product belonging to a category and potentially a sub-category. A potential URL structure could be:\n\n- `/products/[category]/[subCategory]/[productId]`\n\n#### Implementing Catch-all Segments\n\nUsing catch-all segments, we can create a routing mechanism in NextJs that dynamically handles varying URL depths in an elegant and developer-friendly manner.\n\n##### Folder Structure:\n\n```plaintext\n/app\n    /products\n        /[...params]\n            page.js\n```\n\n\n#### Intercepting Multiple URL Parameters\n\nThe catch-all segments enable us to intercept multiple URL parameters, thus providing the flexibility to manage various URL structures:\n\n```plaintext\n/products/one\n/products/one/two\n/products/one/two/three\n```\n\nThis allows you to create a user-friendly URL structure, such as:\n- `/products/electronics`\n- `/products/electronics/phones`\n- `/products/electronics/phones/123`\n\n#### Optional Catch-all Segments\n\nUsing the optional catch-all dynamic segments, we can handle even the root path, preventing 404 errors for URLs like `/products`:\n\n```plaintext\n/app\n    /products\n        /[[...params]]\n            page.js\n```\n\n##### Example URLs:\n\n```plaintext\n/products\n/products/electronics\n/products/electronics/phones\n/products/electronics/phones/123\n```\n\n### Conclusion\n\nImplementing catch-all and optional catch-all segments in NextJs allows developers to create a rich, user-friendly, and SEO-optimized URL strategy, especially beneficial in scenarios like e-commerce platforms where a hierarchical and intuitive navigation system is key to enhancing user experience and SEO.\n\n\n# Introducing the route groups in NextJs 13\n\nIn this Docs, we will see how to use the NextJs route groups to set a shared layout for multiple pages in the app folder.\n\nLet's say we have the following files in the app folder:\n\n```plaintext\n/app\n    page.js -\u003e maps to: /\n    /red\n        page.js -\u003e maps to: /red\n    /blue\n        page.js -\u003e maps to: /blue\n    /green\n        page.js -\u003e maps to: /green\n```\n\nFor the `/red` and `/blue` routes we want to set a shared [layout], but we don't want to have this layout on the `/green` route.\n\nIn order to do this we will need to use the route groups from NextJs.\n\nA route group is created by wrapping a folder’s name in parenthesis:\n\n```plaintext\n(nameOfFolder)\n```\n\nBy adding a route group we are breaking out of the [NextJs route system]. The folders written in round brackets are not included in the application routes.\n\nSo, if we will add put the `red` and `blue` folders in a folder named `(sharedLayout)`, we will still have the same routes as before:\n\n```plaintext\n/app\n    page.js -\u003e maps to: /\n    (sharedLayout)\n        /red\n            page.js -\u003e maps to: /red\n        /blue\n            page.js -\u003e maps to: /blue\n    /green\n        page.js -\u003e maps to: /green\n```\n\nWe can use the route groups to better organize our code.\n\n# Adding shared layouts for multiple pages\n\nBut, one cool thing is that we can also use route groups to share layouts between multiple pages with the same root folder. So, if we will add a `layout.js` file in the `(sharedLayout)` folder:\n\n```plaintext\n/app\n    page.js\n    /(sharedLayout)\n        layout.js\n        /red\n            page.js\n        /blue\n            page.js\n    /green\n        page.js -\u003e maps to: /green\n```\n\nThen the `/red` and `/blue` pages will have the same shared layout file:\n\n```plaintext\n/app/(sharedLayout)/layout.js\n```\n\n\n### Route Handlers\n\nRoute Handlers allow you to create custom request handlers for a given route using the Web Request and Response APIs.\n\n\n\u003cdiv style=\"padding: 10px; border-left: 5px solid #f39c12; background-color: #fffbcc; margin-bottom: 15px;\"\u003e\n    \u003cstrong\u003eGood to Know:\u003c/strong\u003e Route Handlers are only available inside the app directory. They are the equivalent of API Routes inside the pages directory meaning you do not need to use API Routes and Route Handlers together.\n\u003c/div\u003e\n\n**Convention**\nRoute Handlers are defined in a **route.js|ts** file inside the app directory:\n\n```js\nexport async function GET(request) {}\n```\n\n**Supported HTTP Methods**\n\nThe following HTTP methods are supported:**GET, POST, PUT, PATCH, DELETE, HEAD**, and **OPTIONS**. If an unsupported method is called, Next.js will return a 405 Method Not Allowed response.\n\n**Extended NextRequest and NextResponse APIs**\nIn addition to supporting native Request and Response. Next.js extends them with NextRequest and NextResponse to provide convenient helpers for advanced use cases.\n\n\n\n### Introduction to Zod\n\n[Zod](https://github.com/colinhacks/zod) is a JavaScript library that allows for building schemas to validate, parse, and statically type-check data. It's primarily used in TypeScript projects but can be used in JavaScript projects as well.\n\n#### Why Use Zod?\n\n1. **Type Safety:** Zod schemas are used to derive TypeScript types, ensuring type safety without having to duplicate type definitions.\n   \n2. **Validation:** It provides a powerful and easy way to validate data and extract the validated data in a type-safe manner.\n   \n3. **Parsing:** Zod helps in parsing data, ensuring that the data adheres to expected formats and types.\n\n4. **Error Handling:** It provides detailed error messages when data fails validation, making it easier to identify and fix issues.\n\n5. **Lightweight:** Zod is lightweight and has no dependencies, making it a good choice for projects that need to manage their bundle size.\n\n6. **Extensibility:** It allows for creating custom validations using its extensible API.\n\n### Example Usage of Zod\n\nLet's go through a simple example of how Zod can be used to validate and parse data. First, ensure that Zod is installed in your project. If not, you can add it using npm or Yarn:\n\n```sh\nnpm install zod\n```\nor\n```sh\nyarn add zod\n```\n\nBelow is a TypeScript example demonstrating how you might use Zod to validate user data:\n\n```javascript\nimport { z } from 'zod';\n\n// Define a schema\n// Define a Zod schema\nconst PostSchema = z.object({\n    title: z.string(),\n    // Add any additional properties and their validations here\n});\nexport default PostSchema;\n\n// Validate the data\n\nexport const POST = async (req) =\u003e {\n\n    const body = await req.json();\n\n    const result = PostSchema.safeParse(body);\n\n    if (result.success) {\n        // Your logic for handling valid data goes here\n        // You can safely use result.data\n        return NextResponse.json({ message: \"Successful validation\" });\n    } else {\n        // Your logic for handling validation errors goes here\n        return NextResponse.json({\n            message: \"Validation failed\",\n            errors: result.error.errors,\n        });\n    }\n};\n\n\n```\nThe **safeParse** method returns an object with a success boolean property indicating whether the parsing was successful or not. If success is true, the validated data can be accessed via the data property. If success is false, the validation error can be accessed via the error property.\n\n\n\n### Introducing Prisma\n\n#### What is Prisma?\n\nPrisma is a modern database access toolkit that simplifies database access and ensures type safety. It replaces traditional ORMs and simplifies database workflows.\n\n#### Key Features\n\n- **Prisma Client**: An auto-generated query builder that enables type-safe database access.\n- **Prisma Migrate**: A declarative data modeling and migration system.\n- **Prisma Studio**: A modern, intuitive database management UI.\n\n### Getting Started with Prisma\n\n#### Installation\n\nInstall Prisma CLI globally using npm or yarn.\n\n```shell\nnpm install prisma -D\n```\n\n#### Initialization\n\nCreate a new Prisma project or integrate it into an existing project.\n\n```shell\nnpx prisma init\n```\n\n#### Configuring the Database\n\nSpecify your database connection in `prisma/schema.prisma`.\n\n```prisma\ndatasource db {\n  provider = \"postgresql\" // default provider you can use mongodb, mysql or any other database\n  url      = env(\"DATABASE_URL\")\n}\n```\n\n### Prisma Data Types\n\nPrisma supports a variety of data types, here are a few:\n\n- **String**: Text data.\n- **Int**: Integer numbers.\n- **Float**: Floating-point numbers.\n- **Boolean**: True/False values.\n- **DateTime**: Date and time values.\n- **Json**: JSON objects.\n- **Enum**: Enumerated values.\n\n### Prisma Models\n\nModels in Prisma represent the entities of your application domain and are defined in the Prisma schema. They map to tables in the database.\n\n\nThe provided code snippets illustrate the use of `ObjectId` in MongoDB. `ObjectId` is a 12-byte identifier typically employed to uniquely identify documents within a collection. MongoDB automatically generates an `_id` field of type `ObjectId` if a new document doesn't have one. \n\n### Explanation of the Code\n\n#### Using ObjectId\nIt is common practice for the _id field of a MongoDB document to contain an **ObjectId**:\n\n```json\n{\n  \"_id\": {\"$oid\": \"60d599cb001ef98000f2cad2\"},\n  \"createdAt\": {\"$date\": {\"$numberLong\": \"1624611275577\"}},\n  \"email\": \"ella@prisma.io\",\n  \"name\": \"Ella\",\n  \"role\": \"ADMIN\"\n}\n```\nThis JSON-like code represents a MongoDB document, which includes:\n- An `_id` field with an `ObjectId` as a unique identifier for the document.\n- A `createdAt` field with a date as a numeric string. \n- `email`, `name`, and `role` fields as additional data fields.\n\n#### 2. Prisma Model with String Type ID\n```prisma\nmodel User {\n  id       String @id @default(auto()) @map(\"_id\") @db.ObjectId\n  // Other fields\n}\n```\nThis Prisma model represents a `User`:\n- The `id` field is of type `String`, mapped to an `_id` in MongoDB, and it uses an `ObjectId` type in the database. \n- `@default(auto())` ensures that a new `ObjectId` is auto-generated for new documents.\n\n#### 3. Prisma Model with Bytes Type ID\n```prisma\nmodel User {\n  id       Bytes @id @default(auto()) @map(\"_id\") @db.ObjectId\n  // Other fields\n}\n```\nSimilar to the model above, this `User` model uses a `Bytes` type for the `id`, which will also map to MongoDB's `ObjectId`.\n\n### Notes:\n- `ObjectId`: This is a unique identifier used to locate documents within a collection. The `ObjectId` is like a primary key as it's unique across the collection.\n- `@default(auto())`: This Prisma attribute is used to auto-generate `ObjectId` upon the creation of a new document.\n- `@map(\"_id\")`: Maps the `id` field in your Prisma model to the `_id` field in MongoDB.\n- `@db.ObjectId`: Indicates that the field uses MongoDB's `ObjectId` type.\n\n### Important Points:\n1. **Use of `ObjectId`**: It's commonly used in the `_id` field but can also be used in other fields like relation scalars.\n2. **Type of `ObjectId`**: It must be either `String` or `Bytes` in the Prisma model.\n3. **Auto-generation**: By using `@default(auto())`, a new `ObjectId` is automatically generated when a new document is created.\n   \n### Usage in Prisma:\nYou define your Prisma models to interact with MongoDB collections and documents. The defined models must adhere to the structure of the documents in the MongoDB collection for proper interaction. \n\n### Summary:\n- **In MongoDB**: Each document typically has an `_id` field with an `ObjectId` to uniquely identify it.\n- **In Prisma**: Models that interact with MongoDB often map a field to the `_id` of a MongoDB document and utilize `ObjectId` for unique identification. Different attributes and type definitions ensure compatibility and functionality.\n\n\n#### Example: Defining a Simple Model\n\n```prisma\nmodel User {\n   id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n  name  String\n  email String  @unique\n  posts Post[]\n}\n```\n\nHere, `User` is a model with fields `id`, `name`, and `email`. The `posts` field represents a relation to another model, `Post`.\n\n### Creating and Using Models\n\n#### Example: Extending the User Model\n\nLet's extend our `User` model by adding a new model, `Post`.\n\n```prisma\nmodel Post {\n  id String @id @default(auto()) @map(\"_id\") @db.ObjectId\n  title     String\n  content   String?\n  author    User     @relation(fields: [authorId], references: [id])\n  authorId  ObjectId\n}\n```\n\n#### Generating Prisma Client\n\nGenerate Prisma Client based on your data model.\n\n```shell\nnpx prisma generate\n```\n\n\n`npx prisma db push` and `npx prisma generate` are commands provided by Prisma, but they serve different purposes:\n\n### 1. `npx prisma db push`\n\n- **Purpose**: To update the database schema to match the Prisma schema.\n- **Use-case**: Often used in development to quickly iterate over schema changes without having to handle migrations. It is not recommended for use in production.\n- **Behavior**: \n  - It updates the database schema to match the Prisma schema, **without** creating migrations.\n  - It can result in data loss if changes are not backward compatible (such as changing a column type or deleting a column).\n- **Command**:\n  ```sh\n  npx prisma db push\n  ```\n- **Key Considerations**: \n  - It does not handle database migrations or the migration history.\n  - It’s a way to prototype quickly, but for a more controlled and incremental schema update, migrations are preferred.\n\n### 2. `npx prisma generate`\n\n- **Purpose**: To generate Prisma Client based on your Prisma schema.\n- **Use-case**: Used after defining or updating the Prisma schema to ensure that Prisma Client is up to date and can be used in your application code.\n- **Behavior**: \n  - Generates Prisma Client in `node_modules/@prisma/client`.\n  - Does not affect the database schema.\n- **Command**:\n  ```sh\n  npx prisma generate\n  ```\n- **Key Considerations**: \n  - Should be run after every change to the Prisma schema to ensure that the Prisma Client API is updated.\n  - If using Prisma Migrate, it is generally run after migration commands to ensure the client is in sync with the schema.\n\n### In a Typical Development Workflow:\n\n- You define or modify your Prisma schema.\n- If using migrations: \n  - You create a migration using `npx prisma migrate dev --name \u003cmigration-name\u003e`.\n  - The above command also runs `prisma generate` automatically unless configured otherwise.\n- If not using migrations and prototyping:\n  - You push changes to the database using `npx prisma db push`.\n  - You run `npx prisma generate` to update the Prisma Client.\n  \n### Summary:\n\n- `npx prisma db push`: Quick-and-dirty way to update the database schema for prototyping.\n- `npx prisma generate`: Generates/updates Prisma Client to match the Prisma schema and should be run after every schema change.\n\nBoth commands are part of a typical Prisma workflow, but they handle different aspects of it. Always use them as per your requirement in the development or production workflow.\n\n\n\n\n\n#### Using Prisma Client to Access the Database\n\n\n# Best Practice for Instantiating `PrismaClient` with Next.js\n\n## Problem\n\nMany users have encountered the following warning while working with Next.js in development:\n\n\u003e warn(prisma-client) There are already 10 instances of Prisma Client actively running.\n\nRelated discussions and issues are available on this topic.\n\nIn development mode, executing `next dev` clears the Node.js cache upon each run. Consequently, due to hot reloading, a new `PrismaClient` instance is initialized each time, establishing a connection to the database. Rapid instantiation of `PrismaClient` can swiftly exhaust the database connections because each instance maintains its own connection pool.\n\n## Solution\n\nThe optimal solution is to instantiate a single instance of `PrismaClient` and store it on the `globalThis` object. A check should then be implemented to only instantiate `PrismaClient` if it's not already present on the `globalThis` object. If it is present, the existing instance should be reused to prevent the instantiation of additional `PrismaClient` instances.\n\n### Example Code\n\n```javascript\nimport { PrismaClient } from '@prisma/client'\n\nlet prisma\n\n// check if PrismaClient is not on `globalThis` object\nif (process.env.NODE_ENV === 'production') {\n  prisma = new PrismaClient()\n} else {\n  if (!globalThis.prisma) {\n    globalThis.prisma = new PrismaClient()\n  }\n  prisma = globalThis.prisma\n}\n\nexport default prisma\n\n```\n\n\n### Conclusion\n\nPrisma provides a streamlined, type-safe way to interact with your database, manage your data model, and carry out database migrations. Its ease of use, powerful features, and scalability make it an excellent choice for modern application development. Further exploration can be done via [Prisma's documentation](https://www.prisma.io/docs/).\n\n\n### Auto-completion using plain JavaScript\n\nAuto-completion is one of the powerful features provided by Prisma when using TypeScript. However, if you are using plain JavaScript, you might lose some of these capabilities. Nonetheless, you can still enable auto-completion in JavaScript by type-checking your JavaScript files using JSDoc and TypeScript as a background service.\n\nHere's how you might achieve that:\n\n### 1. Install TypeScript (as a devDependency)\n\nEven though you're using JavaScript, installing TypeScript in your project can help VSCode and other editors provide better autocompletion and type checking.\n\n```sh\nnpm install --save-dev typescript\n```\n\n### 2. Configure TypeScript for JSDoc\n\nCreate a `tsconfig.json` file in your project root (if you don't have one already) with the following contents:\n\n```json\n{\n  \"compilerOptions\": {\n    \"allowJs\": true,\n    \"checkJs\": true,\n    \"noEmit\": true,\n    \"strict\": false,\n    \"target\": \"es6\",\n    \"moduleResolution\": \"node\",\n    \"baseUrl\": \".\"\n  },\n  \"include\": [\n    \"next.config.js\",\n    \"**/*.js\"\n  ]\n}\n```\n\n- `\"checkJs\": true` enables type-checking for JavaScript files.\n- `\"noEmit\": true` ensures TypeScript is used only for type-checking and doesn't compile code.\n\n### 3. Use JSDoc for Type Annotations\n\nUse JSDoc comments to annotate types in your JavaScript files. For Prisma, you'll mainly want to type the Prisma client. Here’s an example:\n\n```javascript\n/** @type {import('@prisma/client').PrismaClient} */\nconst prisma = require('@prisma/client');\n```\n\nOr if you are using ES6 imports:\n\n```javascript\nimport prisma from '@prisma/client';\n\n/** @type {import('@prisma/client').PrismaClient} */\nconst prismaClient = prisma;\n```\n\n### 4. Enable Type Checking and Autocompletion in VSCode\n\nIf you're using VSCode, it will automatically pick up the `tsconfig.json` and provide autocompletion and type-checking. If you are using a different editor, you may need to check the specific settings or plugins needed to utilize TypeScript for type checking in JavaScript.\n\n### Notes:\n\n- If you find the type checking too strict or it’s providing unwanted noise, you can adjust the `\"strict\": false` setting in the `tsconfig.json` file.\n- If you've specific files or directories you don't want TypeScript to check, you can adjust or add them to the `\"exclude\"` array in `tsconfig.json`.\n\nto generate random secret number you can use \n\nopenssl rand -base64 32\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmchamoudadev%2Fnextjs-getting-started","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmchamoudadev%2Fnextjs-getting-started","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmchamoudadev%2Fnextjs-getting-started/lists"}