Establishing a user session with Node.js

I am new to the world of node.js and JavaScript in general. I have a piece of code that currently handles login functionality by checking if a user exists in a MYSQL database. This part is functioning correctly.

Now, I wish to improve this feature by creating a session variable for the username that can be used throughout the application. Since I am still learning JavaScript, I am unsure about the existing facilities or best practices for handling sessions.

My goal is to utilize this session variable across the application and also implement a logout feature. Can anyone provide guidance on this or suggest some resources? Thank you.

Here is an excerpt from the code:

var body = '';

console.log("user Login ");

request.on('data', function (data) {
    body += data;
});

request.on('end', function () {
    var obj = JSON.parse(body);
    console.log(JSON.stringify(obj, null, 2));
    var query = "SELECT * FROM Customer where name='"+obj.name+"'";
    response.writeHead(200, {
        'Access-Control-Allow-Origin': '*'
    });

    db.query(
        query,
        [],
        function(err, rows) {
            if (err) {
                response.end('{"error": "1"}');
                throw err;
            }
            if (rows!=null && rows.length>0) {
                console.log(" user in database" );
                theuserid = rows[0].customerID;
                var obj = {
                    id: theuserid
                }
                response.end(JSON.stringify(obj));

            }
            else{
                response.end('{"error": "1"}');
                console.log(" user not in database");
            }

        }
    );
});

}

Answer №1

There are various methods for implementing a user session.

First, one option is to utilize a browser cookie. This approach has its own advantages and disadvantages, so it's important to research how cookies are handled. The effectiveness of this method may also depend on the type of server being used (such as express or hapi).

Another approach is to establish a JWT token on the backend and include it in the response header. Subsequently, you can store this token in either the application state or local storage of the browser to maintain it on the UI. Any subsequent requests that require authentication should include this token in the header for verification.

To gain a deeper understanding, consider exploring related libraries like passport, which can simplify this process.

PS: If opting for cookies, be mindful of obtaining permission from the business as some end-users may not appreciate constant tracking. :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with webpage responsiveness, width not adjusting correctly

Just completed coding my website and now I'm facing a new challenge. I am focusing on making it responsive for tablet screens (768px) starting with the header section, but for some reason, the modifications I make in the responsive.css file are not ta ...

update-post-thumbnail wp-ajax return false

I have been attempting to utilize the media manager within Wordpress. I am using the post editor outside of the admin area, allowing users to create posts with a featured image. I have used the _wp_post_thumbnail_html function to display the image or provi ...

steps to verify the status of a sent request

I am utilizing the contenteditable property in a p tag. My code is as follows: <p contenteditable="true" id="Option1_<?php echo $i ?>" style="width:98%;border:4px thin black; background-color:#D6D6D6;font-size:18px;color:black;padding:3px ">&l ...

Is there a way to display multiple images in a JSON message object?

If you're looking for a fun way to generate random dog images, then check out my DogAPI image generator! Simply enter a number between 1-50 into the form text box, hit send, and watch as it displays that amount of random dog photos. I'm almost t ...

"Encountering an issue with Material UI where the Theme Style typography is not

Trying to update typography in the theme using Material UI but facing issues with object changes not working. The palette, however, is functioning correctly. Attempts were made to modify H3 styles and default font size but without success. On the contrar ...

The Checkbox handler in Material-UI component fails to update the state - Version 5.0

Hey everyone, I'm facing an issue with my "Checkbox" component in React. After clicking on it, the state doesn't update to 'true' as expected. The checkbox works visually in the DOM but the state remains 'false'. Can someone p ...

Why does tsc produce a compiled file that throws an exception when executed, while ts-node successfully runs the TypeScript file without any issues?

I have written two ts files to test a decorator. Here is the content of index.ts: import { lockMethod } from './dec'; class Person { walk() { console.info(`I am walking`); } @lockMethod run() { console.info(`I am running`); } ...

Utilize your access token to send a message through Google Business Messages

Currently, I have successfully set up a method to send messages using the Google Business Messages API from an agent to a user through NodeJS. const bmApi = new businessmessages.businessmessages_v1.Businessmessages({}); This process requires authenticatio ...

What is the best way to incorporate this into a Vue project?

I am in the process of transitioning my code to Vue.js, so I am relatively new to Vue. In the screenshot provided (linked below), you can see that there are 4 columns inside a div with the class name columns. I attempted to use the index, like v-if='i ...

Cease the use of bi-directional data binding on an Angular directive

One way I've been attempting to send information to a directive is through the following setup: <ui-message data="{{app}}"></ui-message> In my controller, this is how I define it: app.controller("testCtrl", function($scope) { $scope.a ...

The process of merging these two functions involves ensuring that one function does not start until the other has successfully completed its task

A closer look at the two functions in question: const handleSubmit = async (e) => { e.preventDefault(); console.log(songLink) const newSong = { songName, songLink, userId }; const song = await dispatch(pos ...

Deactivate or modify the bodyparser function

Is it possible to turn off or replace the bodyparser functionality after adding it as middleware to an express app? In one file (which cannot be edited and is set up by the framework), the bodyParser.json() method is used: app.use(bodyParser.json()); expo ...

In the realm of numeric input in JavaScript (using jQuery), it is interesting to note that the keyCode values for '3' and '#' are identical

I am in need of setting up an <input type="text" /> that will only accept numeric characters, backspace, delete, enter, tabs, and arrows. There are many examples out there, and I started with something similar to this: function isNumericKeyCode (ke ...

How can you set a condition for when no matches are found in a list filter?

I recently came across a fascinating example on W3 Schools that taught me how to implement a search filter. Below, I have customized it for everyone's reference. I am interested in modifying it to only display a list item with the message: No matche ...

Creating a Docker image for a nodejs application starting from a blank slate

I am relatively new to using Docker and I am looking to create a node-js image completely from scratch. I have done some research online, but most images seem to be based on other node-js images. So far, I have attempted to include the node executables a ...

Utilize jQuery and JavaScript dynamically in an HTML document on iOS devices

Having some trouble with this code snippet and getting it to work as intended. - (void)viewDidLoad { [super viewDidLoad]; _webview.delegate = self; [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBun ...

What factors should you consider when deciding between NoSQL and SQL databases?

Here's my query: I am interested in learning Node.js/Express and creating a basic web project. The project would involve setting up a database with tables for users, video games, and categories. The website will simply display a list of games (for de ...

Guide on extracting route details from request object in Node.js/Express

I need to track the route when a request is received in a nodejs (10.16) and express (4.16) project. The server is running on port 3000 at localhost. Let's take a look at the users route: const users = require('../routes/users'); module.ex ...

Using jQuery AJAX to send a URL as a string parameter

Currently, I have an ajax function that sends a string of variables to my script. However, there is one variable that needs to hold a complete URL along with parameters. In the current setup, var1 and var2 are received as $_POST variables. But I specifica ...

Problem with Ionic App crashing

Currently, I am developing an Ionic app that relies on local storage for offline data storage. The app consists of approximately 30 different templates and can accommodate any number of users. Local storage is primarily used to store three key pieces of i ...