### Install Next-Admin Dependencies Source: https://next-admin.js.org/docs/getting-started Install the core package and the Prisma generator. ```bash yarn add @premieroctet/next-admin @premieroctet/next-admin-generator-prisma ``` ```bash npm install -S @premieroctet/next-admin @premieroctet/next-admin-generator-prisma ``` ```bash pnpm add @premieroctet/next-admin @premieroctet/next-admin-generator-prisma ``` -------------------------------- ### Install SWC Plugin for Next-Admin Source: https://next-admin.js.org/docs/getting-started Install the experimental SWC plugin and superjson dependency. ```bash yarn add -D next-superjson-plugin superjson ``` ```bash npm install --save-dev next-superjson-plugin superjson ``` ```bash pnpm install -D next-superjson-plugin superjson ``` -------------------------------- ### NextAdmin Options Configuration Example Source: https://next-admin.js.org/docs/api/model-configuration Example of NextAdmin options configuration, demonstrating how to set the base path, title, and model configurations, including the `edit.display` property for notices. ```typescript export const options: NextAdminOptions = { basePath: "/admin", title: "⚡️ My Admin", model: { User: { /** ...some configuration **/ edit: { display: [ "id", "name", { title: "Email is mandatory", id: "email-notice", description: "You must add an email from now on", } as const, "email", "posts", "role", "birthDate", "avatar", "metadata", ], /** ... some configuration */ }, }, }, }; ``` -------------------------------- ### Install Babel Plugin for Next-Admin Source: https://next-admin.js.org/docs/getting-started Install the required Babel plugin and superjson dependency using your preferred package manager. ```bash yarn add -D babel-plugin-superjson-next superjson@^1 ``` ```bash npm install --save-dev babel-plugin-superjson-next superjson@^1 ``` ```bash pnpm install -D babel-plugin-superjson-next superjson@^1 ``` -------------------------------- ### Creating a Custom Router Adapter for Next-Admin Source: https://next-admin.js.org/docs/frameworks-support This example demonstrates how to create a custom router adapter using `createRouterAdapter` and `createNextAdminComponents`. You need to implement your router logic within `useMyRouterHook`. ```javascript import { createRouterAdapter } from "@premieroctet/next-admin/adapters/context"; import { createNextAdminComponents } from "@premieroctet/next-admin/adapters/components"; import type { RouterInterface } from '@premieroctet/next-admin/adapters/types' const useMyRouterHook = (): RouterInterface => { // My router } export const MyCustomNextAdminRouterAdapter = createRouterAdapter(useMyRouterHook) const { NextAdmin, MainLayout } = createNextAdminComponents( NextAdminRouterAdapter ); export { NextAdmin, MainLayout }; ``` -------------------------------- ### Install Next Admin v5 with npm Source: https://next-admin.js.org/docs/v5-migration-guide Use this command to upgrade the Next Admin package to the latest version using npm. ```bash npm install -S @premieroctet/next-admin@latest ``` -------------------------------- ### Install Next Admin v5 with Yarn Source: https://next-admin.js.org/docs/v5-migration-guide Use this command to upgrade the Next Admin package to the latest version using Yarn. ```bash yarn add @premieroctet/next-admin@latest ``` -------------------------------- ### Using NextAdmin with Custom Dashboard and User Info Source: https://next-admin.js.org/docs/api/next-admin-component This example demonstrates how to use the `` component with a custom dashboard and user information. Ensure `getNextAdminProps` is used to pass necessary props. ```javascript import Dashboard from "path/to/CustomDashboard"; export default function Admin(props: AdminComponentProps) { /* Props are passed from getNextAdminProps function */ return ( ); } ``` -------------------------------- ### Install Next Admin v5 with pnpm Source: https://next-admin.js.org/docs/v5-migration-guide Use this command to upgrade the Next Admin package to the latest version using pnpm. ```bash pnpm install -S @premieroctet/next-admin@latest ``` -------------------------------- ### Configure Next Admin Options Source: https://next-admin.js.org/docs/api/options Use the `options` parameter to customize your admin panel. Centralize this configuration in a single file for reusability. This example demonstrates setting the title, model configuration, custom pages, external links, and sidebar groups. ```javascript import { NextAdminOptions } from "@premieroctet/next-admin"; export const options: NextAdminOptions = { title: "⚡️ My Admin Page", model: { /* Your model configuration here */ }, pages: { "/custom": { title: "Custom page", icon: "AdjustmentsHorizontalIcon", }, }, externalLinks: [ { label: "App Router", url: "/", }, ], sidebar: { groups: [ { title: "Users", className: " bg-green-600 p-2 rounded-md", // group title extra classes. (optional) models: ["User"], }, { title: "Categories", models: ["Category"], }, ], }, }; ``` -------------------------------- ### Define Prisma Schema for NextAdmin Source: https://next-admin.js.org/docs/api/options Example Prisma schema defining a User model with various field types and relations. ```prisma // prisma/schema.prisma enum Role { USER ADMIN } model User { id Int @id @default(autoincrement()) email String @unique name String? password String @default("") posts Post[] @relation("author") // One-to-many relation profile Profile? @relation("profile") // One-to-one relation birthDate DateTime? createdAt DateTime @default(now()) updatedAt DateTime @default(now()) @updatedAt role Role @default(USER) } ``` -------------------------------- ### Intercept Data Submission with Model Hooks Source: https://next-admin.js.org/docs/code-snippets Use `beforeDb` and `afterDb` hooks to intercept data submissions for models. This example adds `createdBy` and `updatedBy` fields and sends an email notification after creation or update. ```javascript { model: { Post: { edit: { hooks: { async beforeDb(data, mode, request) { const userId = 1 // retrieve from the request / cookies, etc // your own permission check if (!userHasPermission(userId)) { throw new HookError(403, { error: "Forbidden" }); } if (mode === "create") { data.createdBy = userId; } else { data.updatedBy = userId; } return data }, async afterDb(data, mode, request) { const userId = 1 // retrieve from the request / cookies, etc sendMail({ to: "some@email.com", subject: "Post updated", text: `Post ${data.title} has been ${mode === "create" ? "created" : "updated"} by ${userId}`, }) } } } } } } ``` -------------------------------- ### Implement CSV Export API Endpoint Source: https://next-admin.js.org/docs/code-snippets Define an API endpoint in your Next.js application to export user data to a CSV file. This example fetches all users and formats them into a CSV string. ```typescript import { prisma } from "@/prisma"; export async function GET() { const users = await prisma.user.findMany(); const csv = users.map((user) => { return `${user.id},${user.name},${user.email},${user.role},${user.birthDate}`; }); const headers = new Headers(); headers.set("Content-Type", "text/csv"); headers.set("Content-Disposition", `attachment; filename="users.csv"`); return new Response(csv.join("\n"), { headers, }); } ``` -------------------------------- ### Pages Router API Route with Role Check Source: https://next-admin.js.org/docs/code-snippets Secure a Pages Router API route by implementing a role check using next-auth. This example ensures that only users with the 'SUPERADMIN' role can proceed. ```typescript export const config = { api: { bodyParser: false, }, }; const { run } = createHandler({ prisma, options, apiBasePath: "/api/admin", schema: schema, onRequest: (req, res, next) => { const session = await getServerSession(req, res, authOptions); const isAdmin = session?.user?.role === "SUPERADMIN"; if (!isAdmin) { return res.status(403).json({ error: 'Forbidden' }) } return next() } }); export default run; ``` -------------------------------- ### Initialize Next-Admin via CLI Source: https://next-admin.js.org/docs/getting-started Use the CLI to initialize required files. Supports Next.js projects only. ```bash npx @premieroctet/next-admin-cli@latest init ``` ```bash npx @premieroctet/next-admin-cli@latest init --help ``` -------------------------------- ### NextAdmin Options Configuration Source: https://next-admin.js.org/docs/api/options The `options` parameter allows you to configure your admin panel to your needs. It is recommended to centralize your options in a single file. ```APIDOC ## NextAdmin Options Parameter ### Description This parameter allows you to configure your admin panel to your needs, including title, model configuration, custom pages, sidebar, external links, and color schemes. ### Properties - **`title`** (String) - The title of the admin dashboard displayed in the sidebar. Defaults to "Admin". - **`model`** (Object) - Configures how your models, their fields, and relations are displayed and edited. Highly configurable. - **`pages`** (Object) - Allows you to add custom sub-pages as sidebar menu entries. The key is the path, and the value is an object with `title` (String) and `icon` (String). - **`sidebar`** (Object) - Customizes the aspect of the sidebar menu. Can include `groups` which is an array of objects, each with a `title` (String) and `models` (Array of Strings). - **`externalLinks`** (Array) - Adds external links to the sidebar menu. Each object requires a `label` (String) and `url` (String). - **`defaultColorScheme`** (String) - Defines a default color palette ('light', 'dark', 'system'). Defaults to 'system'. - **`forceColorScheme`** (String) - Forces a specific color scheme ('light' or 'dark'). ### Request Example ```javascript import { NextAdminOptions } from "@premieroctet/next-admin"; export const options: NextAdminOptions = { title: "⚡️ My Admin Page", model: { /* Your model configuration here */ }, pages: { "/custom": { title: "Custom page", icon: "AdjustmentsHorizontalIcon", }, }, externalLinks: [ { label: "App Router", url: "/", }, ], sidebar: { groups: [ { title: "Users", className: " bg-green-600 p-2 rounded-md", // group title extra classes. (optional) models: ["User"], }, { title: "Categories", models: ["Category"], }, ], }, defaultColorScheme: "dark", forceColorScheme: "light", }; ``` ``` -------------------------------- ### Importing Framework Adapters in Next-Admin Source: https://next-admin.js.org/docs/frameworks-support Import the necessary adapters and components from NextAdmin for your chosen framework. Replace '' with the specific framework you are using. ```javascript import { NextAdminRouterAdapter, NextAdmin, MainLayout } from '@premieroctet/next-admin/adapters/' ``` -------------------------------- ### Create a Custom Page with MainLayout Source: https://next-admin.js.org/docs/code-snippets Use the MainLayout component to create a custom page with the same layout as Next Admin pages. Ensure necessary imports are included. ```tsx import { MainLayout } from "@premieroctet/next-admin"; import { getMainLayoutProps } from "@premieroctet/next-admin/appRouter"; import { options } from "@/options"; import { prisma } from "@/prisma"; const CustomPage = async () => { const mainLayoutProps = await getMainLayoutProps({ basePath: "/admin", apiBasePath: "/api/admin", /*options*/ }); return ( {/*Page content*/} ); }; export default CustomPage; ``` -------------------------------- ### Configure .babelrc Source: https://next-admin.js.org/docs/getting-started Add the superjson-next plugin to your Babel configuration. ```json { "presets": ["next/babel"], "plugins": ["superjson-next"] } ``` -------------------------------- ### Implement Custom Input Widget Source: https://next-admin.js.org/docs/api/components Demonstrates using FormDataProvider and useFormData to manage state in custom input widgets. ```tsx // pages/admin/coupons/batch-upload.tsx import { FormDataProvider, FileWidget, useFormData } from "@premieroctet/next-admin/inputs"; const BatchUploadWidget = () => { const { setFormData } = useFormData(); return { setFormData((old) => ({ ...old, address: e.target.value })); }} /> } export default function BatchUploadPage() { return ( // Wrap your page in a provider to enable // the fields to to plug into it ); } ``` -------------------------------- ### Basic Prisma Client Usage with Next Admin Source: https://next-admin.js.org/docs/new-prisma-client This snippet shows the initial integration of a custom Prisma instance with Next Admin's `getNextAdminProps`. Note the potential TypeScript error. ```javascript import prisma from "./my-prisma-instance" const nextAdminProps = await getNextAdminProps({ params: params.nextadmin, searchParams, basePath: "/admin", apiBasePath: "/api/admin", prisma, // ^^^^^^ ts error: TS does not like that the inferred PrismaClient type does not come different places options, }); ``` -------------------------------- ### Implement Admin Page in App Router Source: https://next-admin.js.org/docs/getting-started Create the dynamic route page for the App Router. Do not use 'use client' in this file. ```typescript import { PageProps } from "@premieroctet/next-admin"; import { getNextAdminProps } from "@premieroctet/next-admin/appRouter"; import { NextAdmin } from "@premieroctet/next-admin/adapters/next"; import { prisma } from "@/prisma"; import "@/styles.css" // .css file containing tailiwnd rules export default async function AdminPage({ params, searchParams, }: PageProps) { // or PromisePageProps for Next 15+ const props = await getNextAdminProps({ params: params.nextadmin, searchParams, basePath: "/admin", apiBasePath: "/api/admin", prisma, /*options*/ }); return ( ); } ``` -------------------------------- ### Configure next.config.js for SWC Source: https://next-admin.js.org/docs/getting-started Register the next-superjson-plugin in your Next.js configuration file. ```javascript module.exports = { // your current config experimental: { swcPlugins: [ [ "next-superjson-plugin", { excluded: [], }, ], ], }, }; ``` -------------------------------- ### Configure Prisma Generator Source: https://next-admin.js.org/docs/getting-started Add the nextAdmin generator to your schema.prisma file. ```prisma generator nextAdmin { provider = "next-admin-generator-prisma" } ``` ```bash yarn run prisma generate ``` -------------------------------- ### Implement Remix Admin Page Source: https://next-admin.js.org/docs/getting-started Use getNextAdminProps to load data for the admin interface in Remix. ```typescript import { AdminComponentProps } from "@premieroctet/next-admin"; import { NextAdmin } from "@premieroctet/next-admin/adapters/remix"; import { getNextAdminProps } from "@premieroctet/next-admin/pageRouter"; import { LoaderFunctionArgs } from "@remix-run/node"; import { useLoaderData } from "@remix-run/react"; import prisma from "database"; import { options } from "../options"; export const loader = async ({ request }: LoaderFunctionArgs) => { return getNextAdminProps({ url: request.url, apiBasePath: "/api/admin", basePath: "/admin", prisma, options, }); }; export default function Admin() { const data = useLoaderData(); return ( ); } ``` -------------------------------- ### Create App Router API Handler Source: https://next-admin.js.org/docs/v5-migration-guide Set up the catch-all API route handler for Next Admin v5 in an App Router project. This handler manages all Next Admin API requests. ```typescript import { createHandler } from '@premieroctet/next-admin/appHandler'; import schema from '@/path/to/json-schema.json'; import prisma from '@/path/to/prisma/client'; import { options } from '@/path/to/next-admin-options'; const { run } = createHandler({ apiBasePath: '/api/admin', prisma, schema, options, // optional }); export { run as DELETE, run as GET, run as POST }; ``` -------------------------------- ### Model Configuration API Source: https://next-admin.js.org/docs/api/model-configuration This section details how to configure individual models within the Next Admin options. ```APIDOC ## Model Configuration API This API allows you to configure how your data models are displayed and managed within Next Admin. You can customize various aspects, including list views, edit forms, and more. ### Configuration Object The `model` property within `NextAdminOptions` accepts an object where keys are model names and values are configuration objects for each model. ```javascript import { NextAdminOptions } from "@premieroctet/next-admin"; export const options: NextAdminOptions = { model: { // Model configurations go here User: { ... }, Post: { ... }, Category: { ... }, }, }; ``` ### Model Properties Each model configuration object can include the following properties: | Name | Description | Default Value | |---|---|---| | `toString` | A function used to display a record in related lists. | `id` field | | `aliases` | An object containing aliases for model fields. | - | | `title` | The name of the model displayed in the sidebar and section titles. | Model name | | `list` | An object containing options for the list view. | - | | `edit` | An object containing options for the edit view. | - | | `actions` | An array of custom actions to be added to the model. | - | | `icon` | The outline HeroIcon name displayed in the sidebar and page titles. | - | | `permissions` | An array specifying restricted permissions for the model. | [`create`, `edit`, `delete`] | ### `list` Property Configuration This property configures the list view for a model. | Name | Type | Description | Default Value | |---|---|---|---| | `search` | Array | An array of fields that are searchable. Nested fields can be accessed using dot notation (e.g., `author.name`). | All scalar fields are searchable by default. | | `display` | Array | An array of fields to display in the list. Can also be an object for virtual fields. | All scalar fields are displayed by default. | | `orderField` | String | The field to use for ordering the list. Must be a numeric field. Disables other sorting types when enabled. | - | | `fields` | Object | An object containing customization values for model fields. | - | | `copy` | Array | An array of fields that are copyable to the clipboard. | `undefined` - no field is copyable by default. | | `defaultSort` | Object | An optional object to determine the default sort order for the list. | - | | `defaultSort.field` | String | The model's field name to which the sort is applied. Mandatory. | - | | `defaultSort.direction` | String | The sort direction to apply (`asc` or `desc`). Optional. | - | | `filters` | Array | Defines a set of Prisma filters that users can choose from in the list view. | - | | `exports` | Object | An object or array containing export configurations. | - | | `defaultListSize` | Number | The default number of items to display per page. Defaults to 10. | 10 | **Note:** The `search` property is only available for `scalar` fields. ``` -------------------------------- ### Implement API Route Handler Source: https://next-admin.js.org/docs/getting-started Set up the API handler for Next.js App and Pages routers. ```typescript import { prisma } from "@/prisma"; import { createHandler } from "@premieroctet/next-admin/appHandler"; const { run } = createHandler({ apiBasePath: "/api/admin", prisma, /*options*/ }); export { run as DELETE, run as GET, run as POST }; ``` ```typescript import { prisma } from "@/prisma"; import { createHandler } from "@premieroctet/next-admin/pageHandler"; export const config = { api: { bodyParser: false, }, }; const { run } = createHandler({ apiBasePath: "/api/admin", prisma, /*options*/, }); export default run; ``` -------------------------------- ### Configure NextAdminOptions Source: https://next-admin.js.org/docs/api/options Configuration object for NextAdmin defining list display, field formatters, validation, and file upload handlers. ```typescript // pages/api/admin/options.ts export const options: NextAdminOptions = { basePath: "/admin", model: { User: { toString: (user) => `${user.name} (${user.email})`, list: { display: ["id", "name", "email", "posts", "role", "birthDate"], search: ["name", "email"], fields: { role: { formatter: (role) => { return {role.toString()}; }, }, birthDate: { formatter: (date) => { return new Date(date as unknown as string) ?.toLocaleString() .split(" ")[0]; }, }, }, }, edit: { display: ["id", "name", "email", "posts", "role", "birthDate"], fields: { email: { validate: (email) => email.includes("@") || "Invalid email", }, birthDate: { format: "date", }, avatar: { format: "file", handler: { upload: async (buffer, infos) => { return "https://www.gravatar.com/avatar/00000000000000000000000000000000"; }, }, }, }, }, }, }, }; ``` -------------------------------- ### User Configuration API Source: https://next-admin.js.org/docs/api/user Defines the user object for display in the sidebar menu. Includes properties for name, picture, and logout handling. ```APIDOC ## User Configuration ### Description This section describes the configuration for the user displayed in the sidebar menu. ### Parameters #### Request Body - **data.name** (String) - Required - The name of the user displayed in the sidebar menu. - **data.picture** (String) - Optional - The URL of the user's avatar displayed in the sidebar menu. - **logout** (RequestInfo, RequestInit? | Function | String) - Optional - Defines the logout behavior. Can be a request tuple for fetching the logout API, a function to call on logout (server action), or a string to redirect to a logout page. ### Request Example ```json { "data": { "name": "John Doe", "picture": "https://example.com/avatar.jpg" }, "logout": "/auth/logout" } ``` ### Response #### Success Response (200) This configuration does not have a direct success response as it's part of the application's setup. #### Response Example N/A ``` -------------------------------- ### GET/POST/DELETE /api/admin/[[...nextadmin]] Source: https://next-admin.js.org/docs/getting-started Handles all admin API requests using a dynamic splat route in Next.js. ```APIDOC ## [ANY] /api/admin/[[...nextadmin]] ### Description Handles all admin-related API requests using the Next-Admin handler. This route must be configured to support dynamic parameters. ### Method GET, POST, DELETE ### Endpoint /api/admin/[[...nextadmin]] ### Request Body - **FormData** (multipart/form-data) - Required - The handler requires bodyParser to be disabled to parse FormData correctly. ### Response #### Success Response (200) - **data** (object) - The requested admin resource or operation result. ``` -------------------------------- ### List View Configuration Source: https://next-admin.js.org/docs/api/model-configuration Configuration options for the list view, including fields, filters, and exports. ```APIDOC ## List View Configuration ### `list.fields` Property The `fields` property is an object that can have the following properties: Name| Type| Description ---|---|--- formatter| Function| a function that takes the field value as a parameter, and returns a JSX node. It also accepts a second argument which is the NextAdmin context sortBy| String| available only on many-to-one models. The name of a field in the related model to apply the sort to. Defaults to the id field of the related model ### `list.filters` Property The `filters` property allows you to define a set of Prisma filters that a user can apply on the list page. It’s an array of the type below: Name| Type| Description| Default Value ---|---|---|--- name| String| a unique name for the filter| - active| Boolean| a boolean to set the filter active by default| false value| String| a where clause Prisma filter of the related model (e.g. Prisma operators)| - group| String| an id that will be used to give filters with the same group name a radio like behavior| - It can also be an async function that returns the above type so that you can have a dynamic list of filters. ### `list.exports` Property The `exports` property is available in the `list` property. It’s an object or an array of objects that can have the following properties: Name| Type| Description| Default Value ---|---|---|--- format| String| a string defining the format of the export. It's used to label the export button| undefined url| String| a string defining the URL of the export action| undefined The `exports` property does not account for active filters. If you want to export filtered data, you need to add the filters to the URL or in your export action. ``` -------------------------------- ### Implement Remix API Handler Source: https://next-admin.js.org/docs/getting-started Handle API requests in Remix using the Next-Admin appHandler. ```typescript import { createHandler } from "@premieroctet/next-admin/appHandler"; import { LoaderFunctionArgs } from "@remix-run/node"; import prisma from "database"; import { options } from "../options"; const nextAdminApi = createHandler({ prisma, apiBasePath: "/api/admin", options, }); // For GET requests export const loader = async ({ request, params }: LoaderFunctionArgs) => { return nextAdminApi.run(request, { params: Promise.resolve({ nextadmin: params["*"]!.split("/"), }), }); }; // For POST, PUT & DELETE requests export const action = async ({ request, params }: LoaderFunctionArgs) => { return nextAdminApi.run(request, { params: Promise.resolve({ nextadmin: params["*"]!.split("/"), }), }); }; ``` -------------------------------- ### Implement Admin Page in Pages Router Source: https://next-admin.js.org/docs/getting-started Create the dynamic route page for the Pages Router. ```typescript import { AdminComponentProps } from "@premieroctet/next-admin"; import { getNextAdminProps } from "@premieroctet/next-admin/pageRouter"; import { NextAdmin } from "@premieroctet/next-admin/adapters/next"; import { GetServerSideProps } from "next"; import { prisma } from " @/prisma"; export default function Admin(props: AdminComponentProps) { return ( ); } export const getServerSideProps: GetServerSideProps = async ({ req }) => await getNextAdminProps({ basePath: "/pagerouter/admin", apiBasePath: "/api/pagerouter/admin", prisma, /*options*/ url: req.url!, }); ``` -------------------------------- ### Configure NextAdmin models Source: https://next-admin.js.org/docs/api/model-configuration Define model-specific settings such as display fields, search criteria, and custom string representations for the admin panel. ```typescript import { NextAdminOptions } from "@premieroctet/next-admin"; export const options: NextAdminOptions = { /* Your other options here */ model: { User: { toString: (user) => `${user.name} (${user.email})`, title: "Users", icon: "UsersIcon", list: { display: ["id", "name", "email", "posts", "role", "birthDate"], search: ["name", "email"], filters: [ { name: "is Admin", active: false, value: { role: { equals: "ADMIN", }, }, }, ], }, edit: { display: [ "id", "name", "email", "posts", "role", "birthDate", "avatar", ], }, }, Post: { toString: (post) => `${post.title}`, }, Category: { title: "Categories", icon: "InboxStackIcon", toString: (category) => `${category.name}`, list: { display: ["name", "posts"], }, edit: { display: ["name", "posts"], }, }, }, }; ``` -------------------------------- ### NextAdmin UI Components Source: https://next-admin.js.org/docs/api/components Next-Admin exports a set of UI components, most of which extend Radix UI primitives. These components are available through the `@premieroctet/next-admin/components` import. ```APIDOC ## Components Next-Admin exports a set of UI components which are, for most of those, extending Radix UI primitives. These components are available through the `@premieroctet/next-admin/components` import. ### `Button` The button element accepts all the base `button` tag attributes and extends it with the following: | Name | Description | Default Value | |---|---|---| | variant | The button variant. Possible values are `default`, `destructive`, `destructiveOutline`, `outline`, `secondary`, `ghost`, `link` | default | | size | The button size. Possible values are `default`, `sm`, `lg` | - | | icon | A boolean indicating the presence of an icon | - | | asChild | A boolean to render a Radix Slot component | - | | loading | A boolean to render a spinner | - | ### `BaseInput` The input component rendered in the Form component. It accepts all the base `input` tag attributes. ### `Switch` The Radix Switch component. ### `Select` The Radix Select component. ### `Checkbox` An implementation of the Radix Checkbox component. It accepts all the props of the Checkbox Root component, and the following: | Name | Description | |---|---| | indeterminate | A boolean to render the checkbox in an indeterminate state | ### `Dropdown` The Radix Dropdown component. ### `Table` The Radix Table component. ### `Tooltip` The Radix Tooltip component. ### `Breadcrumbs` The `Breadcrumb` accepts the following options: ```jsx ``` ### `Spinner` The `Spinner` component is used to display a loading spinner. ``` -------------------------------- ### Create Pages Router API Handler Source: https://next-admin.js.org/docs/v5-migration-guide Set up the catch-all API route handler for Next Admin v5 in a Pages Router project. This handler manages all Next Admin API requests. ```typescript import { createHandler } from '@premieroctet/next-admin/pageHandler'; import schema from '@/path/to/json-schema.json'; import prisma from '@/path/to/prisma/client'; import { options } from '@/path/to/next-admin-options'; export const config = { api: { bodyParser: false, }, }; const { run } = createHandler({ apiBasePath: '/api/admin', prisma, schema, options, // optional }); export default run; ``` -------------------------------- ### Actions Property Configuration Source: https://next-admin.js.org/docs/api/model-configuration Defines custom actions that can be performed on resource records. Supports client-side dialogs or server-side execution. ```APIDOC ## `actions` Property The `actions` property is an array of objects that allows you to define a set of actions that can be executed on one or more records of the resource. On the list view, there is a default action for deletion. The object can have the following properties: Name| Type| Description ---|---|--- title| String| action title that will be shown in the action dropdown id| String| mandatory, action's unique identifier type| String| action type for client side actions, possible value is 'dialog' | 'server'. By default action with no type is executed on the server component| ReactElement| a React component that will be displayed in a dialog when the action is triggered. Its mandatory if the action type `dialog` is specified. See the ClientActionDialogContentProps for the props passed to the component. For a server side action, it is used inside the message shown at the top of the page after the action execution. It receives a prop `message` containing the message to be displayed. Useful in case you want to display custom content, for example as Markdown. className| string| class name applied to the dialog displayed when the action type is set to 'dialog'. action| Function| an async function that will be triggered when selecting the action in the dropdown. Its mandatory if the action type is not specified. Can return a message object to display a message after the action is done or throw an error to display a message canExecute| Function| a function that takes a record as a parameter and returns a boolean. It is used to determine if the action can be executed on the record successMessage| String| a message that will be displayed when the action is successful if action doesn't return a message object errorMessage| String| a message that will be displayed when the action fails if action doesn't return a message object or throw an error with a message depth| Number| a number that defines the depth of the relations to select in the resource. Use this with caution, a number too high can potentially cause slower queries. Defaults to 2. icon| String| the outline HeroIcon name displayed in the actions dropdown for this action ``` -------------------------------- ### createHandler Function Source: https://next-admin.js.org/docs/api/create-handler-function The createHandler function returns an object to intercept all API access. It accepts configuration options for Prisma, request handling, and general options. ```APIDOC ## createHandler() ### Description This function returns an object that allows you to catch all API access. It accepts an object with the following properties: ### Parameters #### Request Body - **prisma** (object) - Required - Your Prisma client instance. - **onRequest** (function) - Optional - A function that is executed before any request. Useful for authentication. - **options** (object) - Optional - Your Next Admin options. ``` -------------------------------- ### Define Custom Actions with Translation Keys Source: https://next-admin.js.org/docs/i18n Use translation keys for action titles and messages to allow the library to handle localization automatically. ```javascript actions: [ { title: "actions.user.email", action: async (...args) => { "use server"; const { submitEmail } = await import("./actions/nextadmin"); await submitEmail(...args); }, successMessage: "actions.user.email.success", errorMessage: "actions.user.email.error", }, ], ``` -------------------------------- ### Translate Model Names and Fields Source: https://next-admin.js.org/docs/i18n Provide a structured object to map model names, plural forms, and field labels to localized strings. ```json { "model": { "User": { // Keep the case sensitive name of the model "name": "User", "plural": "Users", "fields": { "email": "Email", "password": "Password" } } } } ``` -------------------------------- ### Define List Filters in NextAdmin Source: https://next-admin.js.org/docs/api/model-configuration Set up user-filterable data in list views using Prisma operators. Filters can be active by default, grouped, or dynamically generated. ```javascript filters: [ { name: "filter_name", active: true, value: "{ field: { equals: \"value\" } }", group: "group_name" } ] ``` -------------------------------- ### Middlewares Property Configuration Source: https://next-admin.js.org/docs/api/model-configuration Defines functions that execute before record updates or deletions, allowing control over these operations. ```APIDOC ## `middlewares` Property The `middlewares` property is an object of functions executed either before a record’s update or deletion, where you can control if the deletion and update should happen or not. It can have the following properties: Name| Type| Description ---|---|--- edit| Function| a function that is called before the form data is sent to the database. It takes the submitted form data as its first argument, and the current value in the database as its second argument. If false is returned, the update will not happen. delete| Function| a function that is called before the record is deleted. It takes the record to delete as its only argument. If false is returned, the deletion will not happen. ``` -------------------------------- ### Configure TailwindCSS for Next-Admin Source: https://next-admin.js.org/docs/getting-started Configure TailwindCSS to include Next-Admin styles. ```css @import "tailwindcss"; @import "@premieroctet/next-admin/theme"; @source "./node_modules/@premieroctet/next-admin/dist"; ``` ```javascript module.exports = { content: [ "./node_modules/@premieroctet/next-admin/dist/**/*.{js,ts,jsx,tsx}", ], darkMode: "class", presets: [require("@premieroctet/next-admin/preset")], }; ``` -------------------------------- ### ClientActionDialogContentProps Source: https://next-admin.js.org/docs/api/model-configuration Props for the custom dialog component used for client actions. ```APIDOC ## ClientActionDialogContentProps Represents the props that are passed to the custom dialog component. | Name | Type | Description | |---|---|---| | resource | String | the current Prisma model name | | resourceId | String | Number | the selected record id | | data | Record | A record of row's properties with ListDataFieldValue as value | | onClose | Function | a function to close the dialog, it can receive a message object to display a message after the dialog is closed | ``` -------------------------------- ### Configure List Exports in NextAdmin Source: https://next-admin.js.org/docs/api/model-configuration Define export formats and URLs for list data. Note that active filters are not automatically included; they must be added to the URL or export action. ```javascript exports: { format: "csv", url: "/api/export" } ``` -------------------------------- ### Prisma One-to-One Relation (User and Profile) Source: https://next-admin.js.org/docs/edge-cases Illustrates a one-to-one relationship between User and Profile models in Prisma. Note that only one model can hold the relation field, and removing the relation requires removing the field from the model that doesn't own it. ```prisma model User { id Int @id @default(autoincrement()) profile Profile? @relation("profile") } model Profile { id Int @id @default(autoincrement()) bio String? user User? @relation("profile", fields: [userId], references: [id]) userId Int? @unique } ``` -------------------------------- ### Configure List Fields in NextAdmin Source: https://next-admin.js.org/docs/api/model-configuration Customize how fields are displayed and sorted in list views. Use 'formatter' for custom rendering and 'sortBy' for sorting related models. ```javascript fields: { formatter: (value, context) => { // return JSX node }, sortBy: "related_field_name" } ``` -------------------------------- ### App Router Admin Page with Role Check Source: https://next-admin.js.org/docs/code-snippets Protect an App Router admin page by checking user roles with next-auth. Redirects non-admin users to the homepage if they lack the 'SUPERADMIN' role. ```typescript export default async function AdminPage({ params, searchParams, }: { params: { [key: string]: string[] }; searchParams: { [key: string]: string | string[] | undefined } | undefined; }) { const session = await getServerSession(authOptions); const isAdmin = session?.user?.role === "SUPERADMIN"; // your role check if (!isAdmin) { redirect('/', { permanent: false }) } const props = await getNextAdminProps({ params: params.nextadmin, searchParams, basePath: "/admin", apiBasePath: "/api/admin", prisma, schema, }); return ; ``` -------------------------------- ### Define Custom Actions for Resources Source: https://next-admin.js.org/docs/api/model-configuration Use the `actions` property to define custom actions that can be executed on resource records. Actions can be client-side ('dialog') or server-side, with options for custom components, execution logic, and success/error messages. ```typescript { title: "action title that will be shown in the action dropdown", id: "action's unique identifier", type: "dialog" | "server", component: ReactElement, className: "class name applied to the dialog", action: async Function, canExecute: Function, successMessage: String, errorMessage: String, depth: Number, icon: String } ``` -------------------------------- ### NextAdmin Context Properties Source: https://next-admin.js.org/docs/api/model-configuration Provides context information within the NextAdmin application, such as locale and current row data. ```APIDOC ## NextAdmin Context The `NextAdmin` context is an object containing the following properties: Name| Type| Description ---|---|--- locale| String| The locale used by the calling page. (refers to the accept-language header) row| Object| The current row of the list view ``` -------------------------------- ### NextAdmin Input Widgets Source: https://next-admin.js.org/docs/api/components The inputs used across next-admin are available to be used in custom pages. These components are available through the `@premieroctet/next-admin/inputs` import. Most expect to be wrapped within a `FormDataProvider`. ```APIDOC ## Inputs The inputs used across next-admin are available to be used in custom pages. These components are available through the `@premieroctet/next-admin/inputs` import. Most expect to be wrapped within a `FormDataProvider`: ```jsx // pages/admin/coupons/batch-upload.tsx import { FormDataProvider, FileWidget, useFormData } from "@premieroctet/next-admin/inputs"; const BatchUploadWidget = () => { const { setFormData } = useFormData(); return { setFormData((old) => ({ ...old, address: e.target.value })); }} /> } export default function BatchUploadPage() { return ( // Wrap your page in a provider to enable // the fields to to plug into it ); } ``` ### Components | Component | Description | |---|---| | `FileWidget` | Used to upload files. | | `RichTextField` | Used to edit rich text content. | | `SelectWidget` | Used to select a value from a list of options. | | `TextareaWidget` | Used to edit a text area. | | `CheckboxWidget` | Used to select a boolean value. | | `DateTimeWidget` | Used to select a date and time. | | `DateWidget` | Used to select a date. | | `JsonField` | Used to edit a JSON object. | | `NullField` | Used to select a null value. | | `ArrayField` | Used to edit an array of values. | ``` -------------------------------- ### Defining Router Interface for Custom Adapters Source: https://next-admin.js.org/docs/frameworks-support This TypeScript interface defines the contract for a router object that Next-Admin expects. It includes methods for navigation and query manipulation. ```typescript type Query = Record; type PushParams = { pathname: string; query?: Query; }; type Router = { push: (params: PushParams) => void; replace: (params: PushParams) => void; refresh: () => void; setQuery: (query: Query, merge?: boolean) => void; }; type RouterInterface = { router: Router; query: Record; pathname: string; }; ``` -------------------------------- ### Virtual List Fields Source: https://next-admin.js.org/docs/api/model-configuration Configuration for adding custom computed columns to the list panel. ```APIDOC ## Virtual list fields It is possible to add custom columns in the list panel that are computed from the value of other columns. This is done by setting an object in the `list.display` array of a model. This object takes the following properties: | Name | Type | Description | Default Value | |---|---|---|---| | key | String | A unique key used to index the value in the data | - | | label | String | An optional explicit label for the table header. If a translation under the `model.your_resource.fields.your_key`" is provided, this translation will be used, else this label, otherwise the key. | - | | dependsOn | String[] | An array of fields on the current resource that the virtual field depends on. You should typically include fields that are not already in the `display` array. | - | | formatter | Function | A function that takes a NextAdmin context as a parameter, containing the raw data value. This function can either return a string or a react element (currently only for App Router). If a string is returned, a `type` property can be provided to alter the render of the cell in the table. | - | | type | String | An optional type used to alter the render of the cell. Available values are `scalar`, `count`, `date` and `link`. If `link` is used, the `url` function must be provided. | scalar | | url | Function | A function that takes a NextAdmin context as a parameter, containing the raw data value. This function should return a string representing the URL to which the cell should link. | - | ```