Tuesday, 28 January 2025

Lecture Notes Of Class 15: Implementing Sessions and Cookies

 

Lecture Notes Of Class 15: Implementing Sessions and Cookies

Objective:
In this class, you will learn how to manage user sessions and cookies in a web application. The focus will be on using express-session to set up sessions, along with implementing login/logout functionality with session persistence.


What Are Sessions and Cookies?

Before diving into implementation, let’s first understand the concepts of sessions and cookies.

1. Sessions:

  • A session is a server-side storage mechanism that allows the server to store and retrieve data for a user across multiple requests. Each session is identified by a unique session ID.
  • Sessions are typically used to store user-related data, such as login status, preferences, and other sensitive information.
  • express-session is a middleware for Express.js that helps manage sessions easily.

2. Cookies:

  • A cookie is a small piece of data stored on the client's browser. It is sent to the server with every subsequent request to the same domain.
  • Cookies can store information such as user preferences, session identifiers, or tracking information.
  • Cookies are less secure compared to sessions because they are stored on the client-side and can be easily modified.

Setting Up Sessions Using express-session

To manage sessions in your Express.js application, you can use the express-session middleware. Here’s how to set it up:

Step 1: Install express-session

First, you need to install express-session using npm:

bash

CopyEdit

npm install express-session

Step 2: Set up Express and Session Middleware

In your app.js (or server file), you need to import the required packages and configure the session middleware:

javascript

CopyEdit

const express = require('express');

const session = require('express-session');

const app = express();

 

// Middleware for parsing form data

app.use(express.urlencoded({ extended: true }));

 

// Session configuration

app.use(session({

  secret: 'your_secret_key', // a secret key to sign the session ID cookie

  resave: false, // prevent session from being saved if it was not modified

  saveUninitialized: true, // force a session to be saved even if it was not initialized

  cookie: { secure: false } // cookie will not be sent over HTTPS (set to true if using HTTPS)

}));

 

// Route for homepage

app.get('/', (req, res) => {

  res.send('<h1>Welcome to the Home Page</h1>');

});

 

// Start the server

app.listen(3000, () => {

  console.log('Server is running on port 3000');

});

  • Explanation:
    • secret: This is a key used to sign the session ID cookie. It should be kept secret to ensure security.
    • resave: This option determines whether the session should be saved back to the store even if it was not modified.
    • saveUninitialized: If set to true, a session will be created even if no data is added to it.
    • cookie: The secure: false option tells the browser not to send the cookie over HTTPS, but this should be set to true if you're using HTTPS.

Lab Task 1: Implementing Login/Logout Functionality

In this lab task, we will implement a simple login and logout system with session persistence.

Step 1: Create a Simple Login Form

Create a login.html file to allow users to input their login credentials.

html

CopyEdit

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Login</title>

</head>

<body>

  <h2>Login Form</h2>

  <form action="/login" method="POST">

    <label for="username">Username:</label>

    <input type="text" id="username" name="username" required><br><br>

    <label for="password">Password:</label>

    <input type="password" id="password" name="password" required><br><br>

    <button type="submit">Login</button>

  </form>

</body>

</html>

Step 2: Create the Login Route

In your app.js, create a route for handling the login process. This will authenticate the user and store session data.

javascript

CopyEdit

app.post('/login', (req, res) => {

  const { username, password } = req.body;

 

  // Hardcoded username and password for demonstration

  const validUsername = 'user';

  const validPassword = 'password123';

 

  if (username === validUsername && password === validPassword) {

    // Store user data in the session

    req.session.user = { username };

 

    res.redirect('/profile'); // Redirect to the profile page

  } else {

    res.send('Invalid username or password!');

  }

});

  • Explanation:
    • The req.body object contains the username and password from the login form.
    • If the credentials match the hardcoded values, we store the username in the session object, which will persist across requests.

Step 3: Create a Protected Profile Route

Now, let's create a route that shows a user’s profile if they are logged in.

javascript

CopyEdit

app.get('/profile', (req, res) => {

  if (req.session.user) {

    res.send(`<h1>Welcome, ${req.session.user.username}</h1>

              <a href="/logout">Logout</a>`);

  } else {

    res.redirect('/login'); // Redirect to login if the user is not authenticated

  }

});

Step 4: Create the Logout Route

To allow users to log out and destroy their session, add a logout route:

javascript

CopyEdit

app.get('/logout', (req, res) => {

  req.session.destroy((err) => {

    if (err) {

      return res.send('Error destroying session');

    }

    res.redirect('/login');

  });

});

  • Explanation:
    • req.session.destroy(): This method destroys the session, effectively logging the user out.

Lab Task 2: Session Persistence

The session data is stored on the server and will persist as long as the session cookie is valid. To test session persistence:

1.  Start your server.

2.  Open the login page (/login).

3.  Log in using the hardcoded credentials.

4.  You should be redirected to the /profile route and see a personalized welcome message.

5.  Click on the "Logout" link to destroy the session and redirect to the login page.


What Happens Behind the Scenes?

  • When you log in, a unique session ID is created and stored in the session cookie on the client's browser.
  • This session ID is sent back to the server with each request, allowing the server to identify the session and retrieve the stored session data.
  • Once you log out, the session is destroyed, and the session cookie is invalidated.

Conclusion

In this class, you have learned how to:

  • Set up and use sessions with the express-session middleware.
  • Implement a basic login/logout functionality with session persistence.
  • Understand how sessions and cookies work together to manage user authentication.

By using sessions, you can maintain user authentication status across requests, which is essential for creating secure web applications.

4o mini

You said:

Write 10 assignments with solution and explanation in detail on above concept

ChatGPT said:

ChatGPT

Here are 10 assignments on the concept of sessions and cookies in Express.js, focusing on session management and user authentication. Each assignment is followed by a detailed solution and explanation.


Assignment 1: Setup Express and express-session Middleware

Task:

Set up a basic Express application with the express-session middleware.

Solution:

1.  Install the necessary modules:

bash

CopyEdit

npm init -y

npm install express express-session

2.  Create app.js:

javascript

CopyEdit

const express = require('express');

const session = require('express-session');

const app = express();

 

// Use express-session middleware

app.use(session({

  secret: 'your_secret_key',

  resave: false,

  saveUninitialized: true,

  cookie: { secure: false }

}));

 

app.get('/', (req, res) => {

  res.send('<h1>Session Example</h1>');

});

 

app.listen(3000, () => {

  console.log('Server running on port 3000');

});

Explanation:

In this solution, you are setting up an Express server and using the express-session middleware to manage user sessions. The session data will persist for the lifetime of the session.


Assignment 2: Store User Information in a Session

Task:

Create a route that stores user information (like a username) in the session after a GET request.

Solution:

1.  Modify app.js to include the new route:

javascript

CopyEdit

app.get('/set-user', (req, res) => {

  req.session.username = 'JohnDoe';

  res.send('User information saved to session!');

});

2.  Now, visiting /set-user will store the username in the session.

Explanation:

This task demonstrates how to store data in a session. When you access /set-user, the username value is stored in the session, allowing it to persist for the duration of the session.


Assignment 3: Retrieve User Information from Session

Task:

Create a route that retrieves and displays the username stored in the session.

Solution:

1.  Modify app.js:

javascript

CopyEdit

app.get('/get-user', (req, res) => {

  if (req.session.username) {

    res.send(`Username: ${req.session.username}`);

  } else {

    res.send('No user information found in session.');

  }

});

Explanation:

This solution checks if username is stored in the session. If it is, it displays the stored value; otherwise, it returns a message saying no user information is found.


Assignment 4: Implement a Login Route

Task:

Create a simple login route that stores the username in the session upon successful login.

Solution:

1.  Modify app.js:

javascript

CopyEdit

app.use(express.urlencoded({ extended: true }));

 

app.post('/login', (req, res) => {

  const { username } = req.body;

  if (username) {

    req.session.username = username;

    res.send('Login successful!');

  } else {

    res.send('Please provide a username!');

  }

});

2.  You can now send a POST request to /login with the username, and it will store the username in the session.

Explanation:

In this solution, a POST route /login is created to simulate the login process. When a user sends their username, it gets stored in the session.


Assignment 5: Implement a Logout Route

Task:

Create a route to log the user out by destroying the session.

Solution:

1.  Modify app.js:

javascript

CopyEdit

app.get('/logout', (req, res) => {

  req.session.destroy((err) => {

    if (err) {

      return res.send('Error logging out!');

    }

    res.send('Logged out successfully!');

  });

});

Explanation:

The logout route destroys the session, effectively logging the user out. The session is removed from the server, and the user is redirected.


Assignment 6: Protect a Route with Session Validation

Task:

Create a route that displays the user profile, but only if the user is logged in (i.e., if the session exists).

Solution:

1.  Modify app.js:

javascript

CopyEdit

app.get('/profile', (req, res) => {

  if (req.session.username) {

    res.send(`Welcome, ${req.session.username}!`);

  } else {

    res.send('You are not logged in!');

  }

});

Explanation:

The /profile route is protected by checking whether the session contains a username. If the user is logged in (i.e., the session exists), their profile is shown; otherwise, the user is informed that they are not logged in.


Assignment 7: Set Expiry Time for a Session Cookie

Task:

Set a specific expiry time for the session cookie to automatically expire after a certain period.

Solution:

1.  Modify app.js:

javascript

CopyEdit

app.use(session({

  secret: 'your_secret_key',

  resave: false,

  saveUninitialized: true,

  cookie: { secure: false, maxAge: 60000 } // Session expires in 1 minute

}));

Explanation:

The maxAge option sets the expiration time for the session cookie in milliseconds. In this example, the session will expire after 1 minute, and the user will be logged out automatically.


Assignment 8: Set Secure Cookies for HTTPS

Task:

Configure the session to use secure cookies, meaning the cookie will only be sent over HTTPS connections.

Solution:

1.  Modify app.js:

javascript

CopyEdit

app.use(session({

  secret: 'your_secret_key',

  resave: false,

  saveUninitialized: true,

  cookie: { secure: true } // Ensure HTTPS is used

}));

Explanation:

When secure: true is set, cookies are only sent over HTTPS connections. This ensures that the session data is transmitted securely, preventing interception via HTTP.


Assignment 9: Check if Session Exists before Rendering the Page

Task:

Create a route that checks if the session exists before rendering the page. If no session exists, redirect to the login page.

Solution:

1.  Modify app.js:

javascript

CopyEdit

app.get('/dashboard', (req, res) => {

  if (req.session.username) {

    res.send('<h1>Welcome to the Dashboard!</h1>');

  } else {

    res.redirect('/login');

  }

});

Explanation:

The /dashboard route checks if the user is logged in by verifying the session. If the user is not logged in, they are redirected to the /login page.


Assignment 10: Set Multiple Session Values

Task:

Store multiple pieces of user information (e.g., username, email, and role) in the session and retrieve them.

Solution:

1.  Modify app.js:

javascript

CopyEdit

app.post('/set-user-details', (req, res) => {

  req.session.username = 'JohnDoe';

  req.session.email = 'johndoe@example.com';

  req.session.role = 'admin';

  res.send('User details saved to session!');

});

 

app.get('/get-user-details', (req, res) => {

  if (req.session.username) {

    res.send(`Username: ${req.session.username}, Email: ${req.session.email}, Role: ${req.session.role}`);

  } else {

    res.send('No user details found in session.');

  }

});

Explanation:

In this solution, multiple session values are stored, including username, email, and role. The /get-user-details route retrieves these values if they are stored in the session.


Conclusion

These assignments cover the fundamentals of session management and cookies in Express.js. By working through them, you should now be comfortable with handling user authentication, maintaining session data, and controlling access to routes based on session information.

4o mini

You said:

write 50 MCQs for the concept above with explanation

ChatGPT said:

ChatGPT

Here are 50 multiple-choice questions (MCQs) on sessions and cookies in Express.js, along with explanations for each answer:


1. What is the purpose of express-session in Express.js?

a) To handle HTTP requests
b) To manage user sessions
c) To serve static files
d) To parse JSON data

Answer: b) To manage user sessions
Explanation: express-session is a middleware that manages user sessions in Express.js, enabling the storage of session data between requests.


2. Which of the following is required to use sessions in Express?

a) express-session
b) express-session-cookies
c) cookie-parser
d) express-session-helper

Answer: a) express-session
Explanation: The express-session middleware is required to handle sessions in Express.js applications.


3. What type of data can be stored in a session?

a) Only strings
b) Only numbers
c) Any serializable data
d) Only JSON objects

Answer: c) Any serializable data
Explanation: Sessions can store any type of data that can be serialized, such as objects, strings, numbers, etc.


4. Which of the following is true about session.cookie.maxAge?

a) It sets the maximum age of a cookie.
b) It sets the expiration time of the server session.
c) It only affects cookie storage.
d) It is not a valid option in express-session.

Answer: a) It sets the maximum age of a cookie.
Explanation: The maxAge option defines the expiration time of the cookie associated with the session, in milliseconds.


5. What does req.session represent in an Express application?

a) The incoming HTTP request
b) The session data for the current user
c) The session data for all users
d) A list of all cookies for the current user

Answer: b) The session data for the current user
Explanation: req.session is an object that holds the session data specific to the current user.


6. How do you prevent a session from being saved for every request?

a) Set resave to false
b) Set saveUninitialized to false
c) Set secure to true
d) Set maxAge to 0

Answer: a) Set resave to false
Explanation: Setting resave to false prevents the session from being saved on every request, only saving it when necessary.


7. What is the default session expiration time if maxAge is not set?

a) 1 day
b) 1 hour
c) 2 hours
d) The session persists until the browser is closed

Answer: d) The session persists until the browser is closed
Explanation: By default, sessions last as long as the browser session. Once the browser is closed, the session is deleted.


8. What does the cookie.secure option do in a session configuration?

a) Ensures the cookie is only sent over secure (HTTPS) connections.
b) Encrypts the cookie data.
c) Prevents cookies from being accessed by JavaScript.
d) Sets the cookie to be only accessible by the server.

Answer: a) Ensures the cookie is only sent over secure (HTTPS) connections.
Explanation: cookie.secure: true ensures that the session cookie is sent only over secure HTTPS connections, providing a layer of security.


9. How can you store multiple values in a session?

a) req.session.push()
b) req.session.set()
c) Assigning values directly to req.session
d) Using the session object as a database

Answer: c) Assigning values directly to req.session
Explanation: You can store multiple values by directly assigning them to req.session, like req.session.username = 'John';.


10. What happens if req.session.destroy() is called?

a) The session is removed, and the user is redirected to the login page.
b) The session is cleared, but the user remains logged in.
c) The session data is deleted, and the user is logged out.
d) The session is saved and persisted.

Answer: c) The session data is deleted, and the user is logged out.
Explanation: Calling req.session.destroy() deletes the session data, logging the user out.


11. What happens when the session cookie expires?

a) The user remains logged in but cannot access any pages.
b) The session is automatically renewed.
c) The session is destroyed, and the user is logged out.
d) The session cookie is refreshed automatically.

Answer: c) The session is destroyed, and the user is logged out.
Explanation: When the session cookie expires, the session is deleted, and the user is logged out.


12. Which method is used to set a session variable in Express?

a) req.set()
b) req.session.set()
c) req.session['variable'] = value
d) req.add()

Answer: c) req.session['variable'] = value
Explanation: You can set a session variable using the req.session object, like req.session.username = 'John';.


13. In Express, how can you access session data on a subsequent request?

a) req.session.get()
b) req.session
c) session.get()
d) session.retrieve()

Answer: b) req.session
Explanation: Session data can be accessed on subsequent requests through req.session.


14. Which of the following is a valid session configuration option in Express?

a) resave
b) secureCookie
c) sessionLifetime
d) maxSession

Answer: a) resave
Explanation: resave is a valid session option that determines if the session should be saved on every request.


15. What is the default value of saveUninitialized in express-session?

a) false
b) true
c) null
d) undefined

Answer: b) true
Explanation: The default value of saveUninitialized is true, meaning a session will be saved even if it has not been modified.


16. Which of the following is true about cookies in Express?

a) Cookies are always sent with every request.
b) Cookies are only accessible in secure HTTPS requests.
c) Cookies are stored on the server.
d) Cookies can be used to store session data.

Answer: d) Cookies can be used to store session data.
Explanation: Cookies are used to store small pieces of data, such as session identifiers, on the client side.


17. What type of session store does express-session use by default?

a) In-memory store
b) File-based store
c) Redis store
d) MySQL database store

Answer: a) In-memory store
Explanation: By default, express-session uses an in-memory store for session data, which is not recommended for production.


18. What is a major limitation of using the default in-memory store for sessions in Express?

a) It does not persist after server restarts.
b) It is too fast.
c) It uses too much disk space.
d) It is incompatible with HTTPS.

Answer: a) It does not persist after server restarts.
Explanation: The in-memory store does not persist session data after the server restarts, making it unsuitable for production environments.


19. Which of the following methods can be used to store session data permanently?

a) By using express-session alone
b) By using cookie-parser
c) By using a custom session store (e.g., Redis, MongoDB)
d) By setting the secure flag

Answer: c) By using a custom session store (e.g., Redis, MongoDB)
Explanation: To store session data permanently, a persistent session store like Redis or MongoDB must be used.


20. How can you make a session cookie persistent across browser restarts?

a) By setting cookie.maxAge
b) By setting secure to true
c) By setting resave to false
d) By setting saveUninitialized to false

Answer: a) By setting cookie.maxAge
Explanation: By setting cookie.maxAge, you can define a specific expiration time for the cookie, which can make the session persistent across browser restarts.


21. Which of the following is the correct way to store a username in a session?

a) req.session['username'] = 'John';
b) req.session = 'username' => 'John';
c) session.set('username', 'John');
d) req.session.username = 'John';

Answer: d) req.session.username = 'John';
Explanation: The correct way to store a username in a session is req.session.username = 'John';.


22. How does Express handle cookies in a session?

a) It encrypts the cookies automatically.
b) It stores session IDs in cookies for tracking.
c) It does not use cookies.
d) It stores all session data in cookies.

Answer: b) It stores session IDs in cookies for tracking.
Explanation: Express uses cookies to store the session ID, which is then used to retrieve session data stored on the server.


23. Which middleware is required to read cookies in Express?

a) cookie-parser
b) express-cookie
c) session-parser
d) express-cookies

Answer: a) cookie-parser
Explanation: The cookie-parser middleware is required to read cookies in an Express.js application.


24. What is the default name of the session cookie in Express?

a) sid
b) sessionid
c) connect.sid
d) cookie.sid

Answer: c) connect.sid
Explanation: By default, the session cookie is named connect.sid.


25. Which of the following can be done to secure a session in Express?

a) Enable secure cookies only over HTTPS
b) Use a custom session store like Redis
c) Set a longer maxAge for the session cookie
d) All of the above

Answer: d) All of the above
Explanation: All of these actions can improve the security of sessions in Express.


26. Which Express option allows you to configure the session cookie name?

a) cookie.name
b) session.cookieName
c) cookie.name in the session config
d) session.cookie.name

Answer: c) cookie.name in the session config
Explanation: The session cookie name can be configured using cookie.name within the session configuration.


27. How do you clear a specific session variable in Express?

a) req.session.delete('variable')
b) delete req.session.variable
c) req.session.clear('variable')
d) req.session.remove('variable')

Answer: b) delete req.session.variable
Explanation: To clear a session variable, you use the delete operator, e.g., delete req.session.variable.


28. Which of the following methods allows for a session's expiration to be handled more precisely?

a) Using sessionTimeOut
b) Using cookie.maxAge
c) Using secure cookies
d) Using maxSessionTime

Answer: b) Using cookie.maxAge
Explanation: cookie.maxAge allows for more precise control over session expiration.


29. What does setting cookie.httpOnly to true do?

a) Makes the cookie accessible by JavaScript.
b) Restricts the cookie to HTTP requests and prevents access by JavaScript.
c) Forces the cookie to expire on the next request.
d) Makes the cookie visible in the response headers.

Answer: b) Restricts the cookie to HTTP requests and prevents access by JavaScript.
Explanation: Setting cookie.httpOnly to true ensures the cookie is not accessible via JavaScript, improving security.


30. What is a drawback of using an in-memory session store?

a) It does not support HTTPS.
b) It cannot handle large amounts of session data.
c) It does not persist data between server restarts.
d) It uses too much disk space.

Answer: c) It does not persist data between server restarts.
Explanation: The in-memory session store does not persist data when the server restarts.


31. Which of the following will correctly initialize session in Express?

a) app.use(session({ secret: 'mySecret' }));
b) app.use(session({ secure: true }));
c) app.use(cookieParser());
d) app.session({ secret: 'mySecret' });

Answer: a) app.use(session({ secret: 'mySecret' }));
Explanation: This is the correct way to initialize sessions using express-session with a secret key.


32. What does cookie.sameSite option control in a session?

a) Whether the cookie can be sent cross-origin.
b) Whether the cookie is encrypted.
c) Whether the cookie is sent over HTTPS only.
d) Whether the cookie can be accessed by JavaScript.

Answer: a) Whether the cookie can be sent cross-origin.
Explanation: The sameSite option controls whether the cookie should be sent with cross-origin requests.


33. How can you securely store a session cookie in Express?

a) By enabling cookie.secure and using HTTPS
b) By using a custom session store
c) By enabling cookie.httpOnly
d) All of the above

Answer: d) All of the above
Explanation: Using HTTPS, cookie.secure, cookie.httpOnly, and a custom session store all contribute to securing the session.


34. What is the default session store used by Express?

a) Redis
b) MongoDB
c) In-memory store
d) MySQL

Answer: c) In-memory store
Explanation: The default session store in Express is the in-memory store.


35. How can you prevent session data from being saved if it hasn't been modified?

a) By setting resave to false
b) By setting saveUninitialized to false
c) By setting cookie.secure to true
d) By using a custom session store

Answer: a) By setting resave to false
Explanation: Setting resave to false prevents session data from being saved if it hasn’t been modified.


36. Which of the following session properties prevents data from being saved to the store until it has been modified?

a) saveUninitialized
b) resave
c) secure
d) rolling

Answer: a) saveUninitialized
Explanation: Setting saveUninitialized to false prevents saving sessions that haven't been modified.


37. How can you store large amounts of session data in Express?

a) Use the default in-memory store.
b) Store data in a database-backed session store.
c) Compress the session data before storing.
d) Store the session data in a cookie.

Answer: b) Store data in a database-backed session store.
Explanation: To handle large amounts of session data, use a database-backed session store like Redis or MongoDB.


38. Which session configuration option is used to make a session persistent across requests?

a) resave
b) rolling
c) saveUninitialized
d) secure

Answer: b) rolling
Explanation: The rolling option keeps the session active across requests by resetting the expiration time on every request.


39. How does Express.js handle sessions with cookies?

a) Cookies store all session data.
b) Cookies store only the session ID.
c) Cookies store encrypted session data.
d) Cookies do not store session-related data.

Answer: b) Cookies store only the session ID.
Explanation: In Express, cookies store the session ID, and the session data itself is stored server-side.


40. What is the purpose of the express-session middleware?

a) To handle session storage and management.
b) To manage cookies for the user.
c) To parse request headers.
d) To encrypt session data.

Answer: a) To handle session storage and management.
Explanation: express-session handles session storage and management for web applications in Express.js.


41. What is a key feature of the session cookie in Express?

a) It is always encrypted by default.
b) It can be used to track the user’s identity.
c) It expires after every request.
d) It stores all session data directly.

Answer: b) It can be used to track the user’s identity.
Explanation: The session cookie stores the session ID, which can be used to track the user’s identity across requests.


42. Which of the following is NOT a session store available in Express?

a) In-memory store
b) Redis store
c) MongoDB store
d) Postgres store

Answer: d) Postgres store
Explanation: Express doesn’t provide a default Postgres store for sessions, but you can configure it manually.


43. When should cookie.httpOnly be used?

a) When you want to store the session data in cookies.
b) When you want to restrict access to the cookie from JavaScript.
c) When you want the cookie to be accessible in the browser only.
d) When you want the session data to expire.

Answer: b) When you want to restrict access to the cookie from JavaScript.
Explanation: cookie.httpOnly prevents access to the cookie from JavaScript, improving security.


44. Which of the following middleware is used for parsing JSON requests?

a) express.json()
b) cookie-parser
c) express-session
d) body-parser

Answer: a) express.json()
Explanation: express.json() is used to parse incoming JSON requests in Express.js.


45. What is the purpose of session.secret in Express?

a) To encrypt session data.
b) To generate a session ID.
c) To sign the session cookie and prevent tampering.
d) To store session-related data.

Answer: c) To sign the session cookie and prevent tampering.
Explanation: The session.secret is used to sign the session cookie and prevent tampering.


46. How do you check if a session is still valid in Express?

a) Check req.session object.
b) Check req.cookie object.
c) Check req.user object.
d) Check req.sessionID.

Answer: a) Check req.session object.
Explanation: You can check if the session is valid by inspecting the req.session object in your middleware.


47. Which of the following is a session store option for Express.js?

a) express-session-memory
b) express-mongo-session
c) connect-redis
d) express-postgres-store

Answer: c) connect-redis
Explanation: connect-redis is a common session store for Express applications, storing sessions in Redis.


48. How can you set a session cookie to expire after one hour?

a) req.session.cookie.expires = new Date(Date.now() + 3600000);
b) req.session.cookie.maxAge = 3600000;
c) req.session.cookie.maxAge = 1;
d) req.session.cookie.expires = 3600000;

Answer: b) req.session.cookie.maxAge = 3600000;
Explanation: Setting cookie.maxAge to 3600000 milliseconds (1 hour) makes the session cookie expire after one hour.


49. What happens when you access req.session for the first time?

a) A new session is automatically created.
b) The session data is returned as an empty object.
c) A session ID is generated and stored in a cookie.
d) It throws an error.

Answer: a) A new session is automatically created.
Explanation: When req.session is accessed for the first time, a new session is automatically created if one doesn't already exist.


50. Which method is used to end a session in Express?

a) req.session.destroy()
b) req.session.clear()
c) req.session.end()
d) req.session.logout()

Answer: a) req.session.destroy()
Explanation: To end a session in Express, you use req.session.destroy(). This will clear all session data and remove the session ID.

 

No comments:

Post a Comment

Search This Blog

Powered by Blogger.