---
# System prepended metadata

title: index.js file

---

# index.js file
## What is index.js used for?
The index.js file creates the express server and provides an entry point for HTTP requests. It handles the Sessions and some of the Websockets setup. It's also in charge of handling or directing requests and middleware.

### express
Express is a Node.js framework that allows for quick and easy server set up, and provides some additional features to use inside of the server.

Installation:
```
npm install express
```
Basic server setup: 
```javascript=
const express = require('express')

let app = express()
let server = http.createServer(app)

server.listen(process.env.CONTROLLERPORT || 3100, () =>
  console.log(
    `Server listening at http://localhost:${
      process.env.CONTROLLERPORT || 3100
    }`,
    `\n Agent Address: ${process.env.AGENTADDRESS || 'localhost:8150'}`,
  ),
)
```

### express-session
Express-session is a framework that is used for creating and managing session middleware to provide user cookies.

Installation:
```
npm install express-session
```
Example Implementation:
```javascript=
app.use(
  session({
    secret: process.env.SESSION_SECRET,
    cookie: {maxAge: 3600 * 1000, httpOnly: false},
    name: 'sessionId',
    resave: true, // Forces the session to be saved back to the session store, even if the session was never modified during the request.
    rolling: true, // keep updating the session on new requests
    saveUninitialized: false, // don't create a session on any API call where the session is not modified
    secure: true, // only use cookie over https
    ephemeral: false, // delete this cookie while browser close
  }),
)
```

### passport
Passport is Express compatible middleware for Node.js. It is used for authenticating requests and for deciding what to do if the authentication succeeds or fails.

Installation:
```
npm install passport
```
Configure With Express:
```javascript=
app.use(passport.initialize());
```
Configure For Persistant Login Sessions:
```javascript=
app.use(passport.session());
```
Example Implementation: 
```javascript=
passport.authenticate('local', (err, user, info) => {
    if (err) throw err
    if (!user) res.json({ error: 'Username or password is wrong.' })
    else {
      req.logIn(user, (err) => {
        if (err) throw err

        // Put roles in the array
        const userRoles = []
        req.user.Roles.forEach((element) => userRoles.push(element.role_name))

        res.cookie(
          'user',
          { id: req.user.user_id, username: req.user.username, roles: userRoles },
          { httpOnly: false },
        )

        res.json({
          id: req.user.user_id,
          username: req.user.username,
          roles: userRoles,
        })
        console.log(req.user)
      })
    }
  })(req, res, next)
```