AdminJS
Published in

AdminJS

How to connect AdminJS to an existing Node.js/Express/TypeScript/MongoDB application

How to connect AdminJS to an existing Node.js/Express/TypeScript/MongoDB application

Connecting AdminJS to your Node.js app

What is AdminJS?

The main pros of using AdminJS

Connecting an AdminJS dashboard

npm install adminjs @adminjs/express
import express from “express”;
import AdminJS from “adminjs”;
import AdminJSExpress from “@adminjs/express”;
const app = express();// Very basic configuration of AdminJS.const adminJs = new AdminJS({
databases: [], // We don’t have any resources connected yet.
rootPath: ‘/admin’, // Path to the AdminJS dashboard.
});
// Build and use a router to handle AdminJS routes.const router = AdminJSExpress.buildRouter(adminJs);
app.use(adminJs.options.rootPath, router);
// Run the server.app.listen(8080, () =>
console.log(`Example app listening on port 8080!`)
);
AdminJS dashboard view.

Create and pass resources to AdminJS

npm install mongoose @adminjs/mongoose
import mongoose from “mongoose”;
import AdminJSMongoose from “@adminjs/mongoose”;
AdminJS.registerAdapter(AdminJSMongoose)
import { Schema } from “mongoose”;// Define a schema that maps to a MongoDB collection and define the shape of the documents within the selected collection.export const citiesSchema = new Schema({
name: {
// Create a required ‘name’ field.
type: String,
require: true,
},
street: String,
number: Number,
postcode: String,
});
import { Schema } from “mongoose”;export const usersSchema = new Schema({
email: {
type: String,
required: true
},
encryptedPassword: {
type: String,
required: true
},
role: {
type: String,
enum: [“admin”, “restricted”],
required: true
},
});
import { citieSchema } from “./Recources/cities”;
import { usersSchema } from “./Recources/users”;
const Users = mongoose.model(“Users”, usersSchema);
const Cities = mongoose.model(“Cities”, citiesSchema);
const adminJs = new AdminJS({    resources:[
{resource: Users},
{resource: Cities},
],
rootPath: “/admin”, // Path to the AdminJS dashboard.
});
import express from “express”;
import AdminJS from “adminjs”;
import AdminJSExpress from “@adminjs/express”;
import mongoose, {ConnectOptions} from “mongoose”;
import AdminJSMongoose from “@adminjs/mongoose”;
import { citiesSchema } from “./Recources/cities”;
import { usersSchema } from “./Recources/users”;
AdminJS.registerAdapter(AdminJSMongoose);const Users = mongoose.model(“Users”, usersSchema);
const Cities = mongoose.model(“Cities”, citiesSchema);
const app = express();// Very basic configuration of AdminJS.const adminJs = new AdminJS({
resources: [
{
resource: Users,
},
{
resource: Cities,
},
],
rootPath: “/admin”, // Path to the AdminJS dashboard.
});
// Build and use a router to handle AdminJS routes.const router = AdminJSExpress.buildRouter(adminJs);
app.use(adminJs.options.rootPath, router);
// Run the server.const run = async () => {
await mongoose.connect(“mongodb://localhost:27017/tutorial”, {useNewUrlParser: true,} as ConnectOptions);
await app.listen(8080, () => console.log(`Example app listening on port 8080!`));
};
run();
List of your resources in the dashboard menu.
show dbs

Authentication mechanism

npm install bcrypt
npm i — save-dev @types/bcrypt
import bcrypt from “bcrypt”;
{
resource: Users,
options: {
properties: {
encryptedPassword: {
isVisible: false,
},
password: {
type: ‘string’,
isVisible: {
// Make password visible in the edit mode.
list: false,
edit: true,
filter: false,
show: false,
},
},
},
actions: {
new: {
// Hash the password.
before: async (request: ActionRequest) => {
if(request?.payload?.password) {
request.payload = {
…request.payload,
encryptedPassword: await bcrypt.hash(request.payload.password, 10),
password: undefined,
}
}
return request
},
}
}
}
},
AdminJS users view.

Adding an AdminJS login page

const router = AdminJSExpress.buildAuthenticatedRouter(
adminJs,
{
cookieName: “adminjs”,
cookiePassword: “complicatedsecurepassword”,
authenticate: async (email, password) => {
const user = await Users.findOne({ email });
if (user) {
const matched = await bcrypt.compare(password, user.encryptedPassword);
if (matched) {
return user;
}
}
return false;
},
},
null,
// Add configuration required by the express-session plugin.
{
resave: false,
saveUninitialized: true,
}
);
npm install cookie-parser express-session
Default AdminJS login page.

Restricting access to resources based on user access level

const isAdminRole = ({ currentAdmin }: { currentAdmin: CurrentAdmin }) => {
return currentAdmin && currentAdmin.role === “admin”;
};
{
resource: Cities,
options: {
actions: {
// Restrict resource modification.
edit: { isAccessible: canEditCities },
delete: { isAccessible: canEditCities },
},
},
},
Disabled record modification.

Bonus: AdminJS modifications (coming soon)

Connecting the admin dashboard to your existing application

--

--

AdminJS is the world’s leading open-source auto-generated admin panel for your Node.js application that allows you to manage all your data in one place.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Bareja Pawel

Frontend dev with 3years of experience. Core team member at https://adminjs.co. Privately enjoy cycling and eating ;)