Sessions, and Runtime Events

Dean Gladish
5 min readJan 27, 2023

--

What does it mean to host a server? In React, componentDidMount() is requested immediately after partial installation, which means that startups that require DOM nodes should come here; this is where interactions with the DOM start. If you need to download data from a remote end, this is a good place to strengthen your network request. Setting the status this way will start resetting the component data on mount. Since window is client-side, we can use it to change the API URL during runtime by creating a .js file in the public folder, let’s say config.js, and storing all the API URLs in different variables inside the config.js file,¹

{% endraw %}
var BASE_URL = '<API_URL>';
var SETTING_OPTION = true;
{% raw %}²

In order to use the data in the config.js file, we need to configure that file into the app by linking it to the index.html file inside the public folder using the below syntax:³

<script src="%PUBLIC_URL%/config.js"></script>

in this way, the %PUBLIC_URL% gives the URL of the app and we will be able to get the access of all the variables inside the config.js file. All the variables in the config.js will go inside the window object. Hence, to access them use window.variableName. So React provides a way to initially only offer parts to the UI that are immediately available, then to componentDidMount — fire and wait for the completion of your promise to download all the remaining data, and then call setState to update the UI to fully display. For example, an element, most often <input>, <select>, and anchor tag <a>, gets focus and the onFocus event occurs. You can actually prevent the default event by using e.preventDefault(), for which e.default() means that the event has default value. Anyhow for focusOut (and any event we might bring up), the event has the default value.⁴

HTTP being stateless,

so that in order to associate a request to another request you need a way to store the user data between the HTTP requests, brings up the question of transport. How do we transport the data between the client and the server? Cookies and URL parameters both are the ways.⁵

Sessions solve exactly this problem.

That is, they are both readable and on the client side. When you assign a client and ID it makes all further requests using that same ID. Information is stored on the server linked to this ID with the client. We need the Express-session, so install the following code: npm install ---save express-session. We will put the session and cookie parser middleware in place. Example, we will use the default store for storing sessions i.e. memory store. The session middleware handles all things for us i.e. creating the session, setting the session cookie and creating the session object to bridge the front and rear ends of Express.⁶

Whenever a request from the same client, we will have their session information stored with us. We can add more properties to the session object.⁷

var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var app = express();
app.use(cookieParser());
app.use(session({secret: "Shh, it's a secret!"}));
app.get('/', function (req, res) {
if (req.session.page_views) {
req.session.page_views++;
res.send("You visited this page " + req.session.page_views + " times");
} else {
req.session.page_views = 1;
res.send("Welcome to this page for the first time!");
}
});
app.listen(3000);⁸

What the above code does, is when a user visits the site, it creates a new session for the user and assigns a cookie. Next time the cookie is checked and the “page-view” session variable is updated accordingly. The res object specifies the HTTP response which is sent by an Express app when it gets the HTTP request.

Dwell Around CORS

CORS (Cross Origin Resource Sharing) is a simple mechanism to let a web app running at one origin, to access resources securely at another origin with permissions. This permission is more of a mechanism with headers for security reasons standard, as browsers restrict cross-origin HTTP requests initiated from within scripts to help mitigate the risk. Now let us know about the CORS preflight request; a small request that is sent by the browser before the actual request. It contains information like which HTTP method is used, as well as if any custom HTTP headers are present. The preflight gives the server a chance to examine what the actual request looks like before it is made. The server can then indicate whether the browser should send the actual request, or return an error to the client without sending the request.⁹

Let us think about a preflight request in the context of the ATM example. Banks sometimes put their ATMs inside a room behind a locked door. The door can only be unlocked by swiping your ATM card. Once you are inside, you can walk up to the ATM and withdraw money. The simple act of swiping your card to unlock the door doesn’t automatically give you money, but it is a quick check to verify that you have permission to use the ATM. In a similar fashion, a preflight request asks for the server’s permission to send the request. The preflight isn’t the request itself. Instead, it contains metadata about it, such as which HTTP method is used and if the client added additional request headers. The server inspects this metadata to decide whether the browser is allowed to send the request.¹⁰

Object-Relational Mapping

As a way to validate key-value pairs, it provides an object-oriented layer between relational databases and object-oriented programming languages. A key value pair stored on a JSON object with some associated key and a value pair, makes it easy to save data for our real-time database.

{ "users": {
"account" {
"name": "Jimmy",
"contact": {
"address": true },
}
}
}¹¹

[1] ReactDOMServer — React
https://reactjs.org/docs/react-dom-server.html

[2] Using {% raw %} in templates does not stop jinja2 variable substitution · Issue #4638 · ansible/ansible
https://github.com/ansible/ansible/issues/4638

[3] How To Work with Files using the fs Module in Node.js | DigitalOcean
https://www.digitalocean.com/community/tutorials/how-to-work-with-files-using-the-fs-module-in-node-js

[4] Adding configurations to your React App at Runtime — DEV Community 👩‍💻👨‍💻
https://dev.to/hey_yogini/react-adding-configurations-to-your-app-at-runtime-2ihm

[5] Using HTTP cookies — HTTP | MDN
https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

[6] ExpressJS — Sessions
https://www.tutorialspoint.com/expressjs/expressjs_sessions.htm

[7] Session Object (IIS) | Microsoft Learn
https://learn.microsoft.com/en-us/previous-versions/iis/6.0-sdk/ms524319(v=vs.90)

[8] Express cookie-parser middleware
https://expressjs.com/en/resources/middleware/cookie-parser.html

[9] Cross-Origin Resource Sharing (CORS) — HTTP | MDN
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

[10] Chapter 4. Handling preflight requests · CORS in Action: Creating and consuming cross-origin APIs
https://livebook.manning.com/book/cors-in-action/chapter-4/

[11] NoSQL Tutorial: What is, Types of NoSQL Databases & Example
https://www.guru99.com/nosql-tutorial.html

--

--