Documentation
API

API

Functions

The following is used only for App router.

getPropsFromParams function

getPropsFromParams is a function that returns the props for the NextAdmin component. It accepts one argument which is an object with the following properties:

  • params: the array of route params retrieved from the optional catch-all segment (opens in a new tab)
  • searchParams: the query params retrieved from the page (opens in a new tab)
  • options: the options object
  • schema: the json schema generated by the prisma generate command
  • prisma: your Prisma client instance
  • action: the server action (opens in a new tab) used to submit the form. It should be your own action, that wraps the submitForm action imported from @premieroctet/next-admin/dist/actions.
  • deleteAction: the server action (opens in a new tab) used to delete one or more records in a resource. It is optional, and should be your own action. This action takes 3 parameters: model (the model name) and ids (an array of ids to delete). Next Admin provides a default action for deletion, that you can call in your own action. Check the example app for more details.
  • getMessages: a function with no parameters that returns translation messages. It is used to translate the default messages of the library. See i18n for more details.

Authentication

The library does not provide an authentication system. If you want to add your own, you can do so by adding a role check in the page:

The following example uses next-auth (opens in a new tab) to handle authentication

// app/admin/[[...nextadmin]]/page.tsx
 
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 getPropsFromParams({
    params: params.nextadmin,
    searchParams,
    options,
    prisma,
    schema,
    action: submitFormAction,
  });
 
  return <NextAdmin {...props} dashboard={Dashboard} />;
}

<NextAdmin /> component

<NextAdmin /> is a React component that contains the entire UI of Next Admin. It can take several props:

  • AdminComponentProps, which are passed by the router function via getServerSideProps
  • options used to customize the UI, like field formatters for example. Do not use with App router.
  • dashboard used to customize the rendered dashboard
  • translations used to customize some of the texts displayed in the UI. See i18n for more details.

⚠️ : Do not override these AdminComponentProps props, they are used internally by Next Admin.

This is an example of using the NextAdmin component with a custom Dashboard component and options:

// pages/admin/[[...nextadmin]].tsx
import Dashboard from "../../components/CustomDashboard";
 
export default function Admin(props: AdminComponentProps) {
  /* Props are passed from the nextAdminRouter function via getServerSideProps */
  return (
    <NextAdmin
      {...props}
      dashboard={Dashboard}
      options={{
        model: {
          User: {
            list: {
              display: ["id", "name", "email", "posts", "role", "birthDate"],
              search: ["name", "email"],
              fields: {
                role: {
                  formatter: (role) => {
                    return <strong>{role.toString()}</strong>;
                  },
                },
                birthDate: {
                  formatter: (date) => {
                    return new Date(date as unknown as string)
                      ?.toLocaleString()
                      .split(" ")[0];
                  },
                },
              },
            },
          },
        },
      }}
    />
  );
}

Next Admin Options

Next Admin options is the third parameter of the router function and it's an object of options that has the following properties:

basePath

basePath is a string that represents the base path of your admin. (e.g. /admin) - optional.

model

model is an object that represents the customization options for each model in your schema.

It takes as key a model name of your schema as value an object to customize your it.

By default if no models are defined, they will all be displayed in the admin. If you want more control, you have to define each model individually as empty objects or with the following properties:

NameDescriptionDefault value
toStringa function that is used to display your record in related listid field
aliasesan object containing the aliases of the model fields as keys, and the field nameundefined
titlea string used to display the model name in the sidebar and in the section titleModel name
listan object containing the list optionsundefined
editan object containing the edit optionsundefined
actionsan array of actionsundefined

You can customize the following for each model:

  • list property

This property determines how your data is displayed in the List View

NameDescriptionDefault value
searchan array of searchable fieldsundefined - all scalar fields are searchable
displayan array of fields that are displayed in the listundefined - all scalar fields are displayed
fieldsan object containing the model fields as keys, and customization values, see belowundefined

Note that the search property is only available for scalar fields.

  • edit property

This property determines how your data is displayed in the edit view

NameDescriptionDefault value
displayan array of fields that are displayed in the formall scalar fields are displayed
stylesan object containing the styles of the formundefined
fieldsan object containing the model fields as keys, and customization valuesundefined
styles property

The styles property is available in the edit property.

⚠️ If your options are defined in a separate file, make sure to add the path to the content property of the tailwind.config.js file

 
| Name    | Description                                                                    |
| ------- | ------------------------------------------------------------------------------ |
| `_form` | a string defining the classname of the form                                    |
| ...     | all fields of the model, with the field name as key and the classname as value |
 
Here is an example of using `styles` property:
 
```ts
styles: {
  _form: "form-classname",
  ... // all fields
};
fields property

The fields property is available in both list and edit properties.

For the list property, it can take the following:

NameDescription
formattera function that takes the field value as a parameter, and that return a JSX node. It also accepts a second argument which is the NextAdmin context

For the edit property, it can take the following:

NameDescription
validatea function that takes the field value as a parameter, and that returns a boolean
formata string defining an OpenAPI field format, overriding the one set in the generator. An extra file format can be used to be able to have a file input
inputa React Element that should receive CustomInputProps. For App Router, this element must be a client component.
handleran object that can take the following properties
handler.geta function that takes the field value as a parameter and returns a transformed value displayed in the form
handler.uploadan async function that is used only for formats file and data-url. It takes a buffer as parameter and must return a string. Useful to upload a file to a remote provider
optionFormatteronly for realtion fields, a function that takes the field values as a parameter and returns a string. Useful to display your record in related list

pages

pages is an object that allows you to add your own sub pages as a sidebar menu entry. It is an object where the key is the path (without the base path) and the value is an object with the following properties:

NameDescription
titlethe title of the page displayed on the sidebar

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 take the following properties:

NameDescriptionDefault value
titleaction title that will be shown in the action dropdownundefined
actionan async function that will be triggered when selecting the action in the dropdown. For App Router, it must be defined as a server action.undefined
successMessagea message that will be displayed when the action is successfulundefined
errorMessagea message that will be displayed when the action failsundefined

Here is an example of using NextAdminOptions for the following schema :

// 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)
}
// pages/api/admin/[[...nextadmin]].ts
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 <strong>{role.toString()}</strong>;
            },
          },
          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 (file: Buffer) => {
                return "https://www.gravatar.com/avatar/00000000000000000000000000000000";
              },
            },
          },
        },
      },
    },
  },
};
 
const adminRouter = await nextAdminRouter(prisma, schema, options);

CustomInputProps

This is the type of the props that are passed to the custom input component:

NameDescription
namethe field name
valuethe field value
onChangea function taking a ChangeEvent (opens in a new tab) as a parameter
readonlyboolean indicating if the field is editable or not
rawErrorsarray of strings containing the field errors

NextAdmin Context

The NextAdmin context is an object containing the following properties:

  • locale: the locale used by the calling page. (refers to the accept-language header).