- [Instructor] As shown in the previous video
we will need cookie parser to read
cookies from the raw request header.
So I'm installing that now
in npm install --save cookie-parser
and we need to recall it in our app.js file.
So somewhere on top of the file add,
const cookieParser = require('cookie-parser').
CookieParser is a middleware.
This means we also have to add it to the chain
of middlewares via app.use.
And for that I'm going down to line 24,
right after the bodyParser.
I will now add app.use(cookieParser).
And we're calling it as a function
So we have to add parentheses here in the end.
From now on Express will give us cookies in request.cookies.
Next, let's plug in the session management.
For that install express session
into install-- save express-session
and to store the sessions in MongoDB I will install
connect-mongo and now on top of app.js again
I will bring in those modules first.
The session module const session =
require('express-session') and then I add the MongoStore.
It's require('connect-mongo').
And this module now takes,
the previously required session as an argument.
Further down now of course we have
to add all of this as a middleware.
So right after line 26 where we added the cookieParser
I will now add app.use(session
and session takes a property object as a argument.
First we define the secret.
This is used to sign the sessions to prevent tamperings.
While I, use some random string here.
Then we want to resave, which means that the session
will stay active also, if it wasn't changed.
And we set saveUninitialized to false
because otherwise we would get a lot
of empty objects in our database.
And now we define a session store.
And this session store is a new MongoStore
and it takes a Mongoose connection, configuration property.
And this should be mongoose.connection.
And as you see, eslint complains now
that mongoose is not defined yet.
Of course we have to also bring it in here
const mongoose = require('mongoose').
And this mongoose module actually,
contains the database connection.
So why can we do it like that
without connecting to the database here?
As I said, when we covered Mongoose,
this module remains in module global state.
And this means that once Mongoose is connected,
and we do that in ping www the connection is available
whenever we require mongoose.
To try the session management out now
let's simply add a little visit counter
to an existing custom middleware
like the one that fetches speaker names.
You will find that, down starting at line 36
here in the try block I add req.session.visits =
and I'm using a ternary operation here,
request.session.visits.
If this is present we will simply add one to this property
and if it's not present it will be initialized with one.
Next we can go ahead and try this out and look at the data
in the debugger and in the database.