Documentation
API

API

nextAdminRouter function

nextAdminRouter is a function that returns a promise of a Node Router that you can use in your getServerSideProps function to start using Next Admin.

Usage example:

// pages/api/admin/[[...nextadmin]].ts
export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
  const { nextAdminRouter } = await import(
    "@premieroctet/next-admin/dist/router"
  );
  const adminRouter = await nextAdminRouter(prisma, schema);
  return adminRouter.run(req, res) as Promise<
    GetServerSidePropsResult<{ [key: string]: any }>
  >;
};

It takes 3 parameters:

  • Your Prisma client instance, required
  • Your Prisma schema, required

and an optional object of type NextAdminOptions to customize your admin with the following properties:

import { NextAdminOptions } from "@premieroctet/next-admin";
 
const options: NextAdminOptions = {
  model: {
    User: {
      toString: (user) => `${user.email} / ${user.name}`,
    },
  },
};
 
const adminRouter = await nextAdminRouter(prisma, schema, options);

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 to the getServerSideProps function:

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

// pages/api/admin/[[...nextadmin]].ts
 
export const getServerSideProps: GetServerSideProps = async ({ req, res }) => {
  const session = await getServerSession(req, res, authOptions);
  const isAdmin = session?.user?.role === "SUPERADMIN"; // your role check
 
  if (!isAdmin) {
    return {
      redirect: {
        destination: "/",
        permanent: false,
      },
    };
  }
 
  const { nextAdminRouter } = await import(
    "@premieroctet/next-admin/dist/nextAdminRouter"
  );
  return nextAdminRouter(client).run(req, res);
};

<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
  • dashboard used to customize the rendered dashboard

⚠️ : 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:

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

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 fieldsall fields are searchable
displayan array of fields that are displayed in the listall fields are displayed
fieldsan object containing the model fields as keys, and customization valuesundefined

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 fields are displayed
fieldsan object containing the model fields as keys, and customization valuesundefined
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

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
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

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);