Skip to content

Instantly share code, notes, and snippets.

@chodorowicz
Last active March 13, 2017 02:55
Show Gist options
  • Save chodorowicz/15290419a550e87253cfe10dacf90a54 to your computer and use it in GitHub Desktop.
Save chodorowicz/15290419a550e87253cfe10dacf90a54 to your computer and use it in GitHub Desktop.
express.js
require('dotenv').config({ silent: true });
var express = require('express');
var app = express();
var port = process.env.PORT || 3002;
var smptSender = require('./smtp-sender');
var bodyParser = require('body-parser')
const compress = require('compression');
const nunjucks = require('nunjucks');
const isDeveloping = process.env.NODE_ENV !== 'production';
function getConfig() {
return {
areAnalyticsEnabled: process.env.ARE_ANALYTICS_ENABLED ? JSON.parse(process.env.ARE_ANALYTICS_ENABLED) : false,
isHotjarEnabled: process.env.IS_HOTJAR_ENABLED ? JSON.parse(process.env.IS_HOTJAR_ENABLED) : false,
};
}
const nunjucksConfig = {
autoescape: true,
express: app,
};
if (isDeveloping) {
nunjucksConfig.noCache = true;
nunjucksConfig.watch = true;
}
nunjucks.configure(['./frontend/templates', './frontend/templates/pages'], nunjucksConfig);
app.engine('html', nunjucks.render);
app.set('view engine', 'nunjucks');
app.use(bodyParser.json());
app.use(compress());
app.use(express.static(__dirname + '/web/'));
app.get('/', (req, res, next) => {
res.render('index', getConfig());
});
/** dynamicaly serve templates */
app.get('/:page.:ext', (req, res, next) => {
if(req.params.ext === 'html') {
res.render(req.params.page, getConfig(), (error, html) => {
if(error) res.redirect('/404');
else res.send(html);
});
}
else next();
});
app.get('*', function(req, res){
res.redirect('/404.html');
});
app.listen(port);
console.log('Listening on port ' + port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment