How to Add Keystone to an Already Existing Express App

Peter Piekarczyk edited this page Apr 14, 2017 · 12 revisions

Home > Knowledge Base > Adding keystone to existing Express app

How to add keystone to an existing Express app

The idea here is to minimally add keystone to your app. This gives you an admin panel at '/keystone' and models(called lists in keystone). With this in place you can use keystone.list to access your data.

var express = require('express'),
    app = express(),
    keystone = require('keystone'),
    serve = require('serve-static'),
    favicon = require('serve-favicon'),
    body = require('body-parser'),
    cookieParser = require('cookie-parser'),
    multer = require('multer');

var cookieSecret = 'secretCookie';

app.use(cookieParser(cookieSecret));
app.use(body.urlencoded({ extended: true }));
app.use(body.json());
app.use(multer());

keystone.init({
  'name': 'Website Name',
  'brand': 'Website Brand',
  'session': false,
  'updates': 'updates',
  'auth': true,
  'user model': 'User',
  'auto update': true,
  'cookie secret': cookieSecret,
});

// Let keystone know where your models are defined. Here we have it at the `/models`
keystone.import('models');

// Serve your static assets
app.use(serve('./public'));

// This is where your normal routes and files are handled
app.get('/', function(req, res, next) {
  res.send('hello world');
});
keystone.app = app;
keystone.start();

Caveats

  • Running an express server is not necessary. If you try running Keystone and the express server on the same port, you'll run into a few errors
  • Make sure to create folders for updates and models. You can copy the generated basic data from the Yeoman Generator
  • Make sure you're using multer@0.1.8. The latest's multer's API changes. If you find yourself getting a TypeError app.use() middleware, this is the problem
  • Make sure you set up your environment variables. If you want to use .env, add require('dotenv').load() to your index.js
  • If you aren't getting anything back from your database, set a website {name,brand} (or manually set up your mongoose)

Errors

Error: cookieParser("secret") required for signed cookies Make sure you set a cookie secret inside cookieParser

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.