+3 votes
189 views
by (3k points)

How to configure sessions ExpressJS?


1 Answer

+4 votes
by (3k points)

requirements
Express Session
cookie Parser

The sessions is something that can not miss on a web server, in this tutorial we will learn to configure your server to accept Express sessions.

Remember that when you create a server with ExpressJS , the server comes without any setup and that is where we must go adding what we believe necessary.Sessions is inevitable for any web application, so let's learn how to properly configured on a server Express.

requirements

To set up sessions before you need to set something else, that are cookies, for this we use a module called cookie-parser .

cookie Parser

Cookie Parser is a module that can be installed via npm  and allows us to set cookies within our server, so we now have to install it .

$ Npm install cookie-parser

If you want the unit is saved in your package.json use --save . Now for the cookie settings.

// Server.js 
'use strict' 
const express =  require ( 'express' ) , 
      cookieParser =  require ( 'cookie-parser' ) ;

const app =  express ( ) ;

app . use ( cookieParser ( ) ) ; 
app . listen ( 8000 ) ;

app  is express our server, to use cookies should only require the module, and use the server express app.use () .

Now we can configure sessions to sessions must use a module called express-session .

Express Session

This like any other module Node is instable via npm .

$ Npm install express-session

You know that the --save is optional. We go to the configuration.

Server.js // 
const session =  require ( 'express-session' ) ;

app . use ( session ( { 
    secret :  'keyboard cat' , 
    resave :  false , 
    saveUninitialized :  true 
} ) )

Remember that for that server must have their express, you can review the settings for cookies. Sessions can receive more than 3 parameters, this depends on what you need, so you can check the express-session documentation for the detail of each parameter. 

With this we will have available the variable req.session in their controllers, and also a unique id for a user session can be accessed via the variable   req.sessionID . 

With this we have our express server configured with sessions and cookies, remember that we also have courses Node.js and Fundamentals of Node.js where we explain this and many other things in more detail.


Welcome to Howconnection Q&A, where you can ask questions and receive answers from other members of the community.

Categories

10.9k questions

10.9k answers

178 comments

4 users

statcounter statistics counter
...