-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
64 lines (53 loc) · 1.9 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/* eslint-disable no-console */
// customising the .env file in your project's root folder.
require('dotenv').config();
const cors = require('cors');
const path = require('path');
const next = require('next');
const morgan = require('morgan');
const express = require('express');
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const { name, version } = require('./package.json');
const dev = process.env.NODE_ENV !== 'production';
if (!process.env.MONGO_URI) {
throw new Error('Cannot start application without process.env.MONGO_URI');
}
// Connect to database
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true });
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));
// Create next.js application
const app = next({
dev,
dir: path.join(__dirname, './client'),
});
// Prepare next.js application
app.prepare().then(() => {
const handle = app.getRequestHandler();
// Create and config express application
const server = express();
server.use(cookieParser());
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
server.use(cors());
server.use(morgan(dev ? 'tiny' : 'combined'));
server.use(
session({
resave: false,
saveUninitialized: true,
secret: process.env.COOKIE_SECRET,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
})
);
// eslint-disable-next-line global-require
require('./server/routes')(server);
server.get('*', (req, res) => handle(req, res));
const port = parseInt(process.env.PORT, 10) || parseInt(process.env.APP_PORT, 10) || 3000;
server.listen(port, err => {
if (err) throw err;
console.log(`> ${name} v${version} ready on ${process.env.BASE_URL}`);
});
});