Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

The Pros and Cons of LocalStorage in Modern Web Development

20 February 2025 at 16:26

Introduction

The Web storage api is a set of mechanisms that enable browsers to store key-value pairs. Before HTML5, application data had to be sorted in cookies, included in every server request. Its intended to be far more user-friendly than using cookies.

Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance.

There are 2 types of web storage,

  1. Local Storage
  2. Session Storage

We already have cookies. Why additional objects?

Unlike cookies, web storage objects are not sent to server with each request. Because of that, we can store much more. Most modern browsers allow at least 5 megabytes of data (or more) and have settings to configure that.

Also unlike cookies, the server can’t manipulate storage objects via HTTP headers. Everything’s done in JavaScript.The storage is bound to the origin (domain/protocol/port triplet). That is, different protocols or subdomains infer different storage objects, they can’t access data from each other.

In this guide, you will learn/refresh about LocalStorage.

LocalStorage

The localStorage is property of the window (browser window object) interface allows you to access a Storage object for the Document’s origin; the stored data is saved across browser sessions.

  1. Data is kept for a longtime in local storage (with no expiration date.). This could be one day, one week, or even one year as per the developer preference ( Data in local storage maintained even if the browser is closed).
  2. Local storage only stores strings. So, if you intend to store objects, lists or arrays, you must convert them into a string using JSON.stringfy()
  3. Local storage will be available via the window.localstorage property.
  4. What’s interesting about them is that the data survives a page refresh (for sessionStorage) and even a full browser restart (for localStorage).

Functionalities

// setItem normal strings
window.localStorage.setItem("name", "goku");

// getItem 
const name = window.localStorage.getItem("name");
console.log("name from localstorage, "+name);

// Storing an Object without JSON stringify

const data = {
  "commodity":"apple",
  "price":43
};
window.localStorage.setItem('commodity', data);
var result = window.localStorage.getItem('commodity');
console.log("Retrived data without jsonified, "+ result);

// Storing an object after converting to JSON string. 
var jsonifiedString = JSON.stringify(data);
window.localStorage.setItem('commodity', jsonifiedString);
var result = window.localStorage.getItem('commodity');
console.log("Retrived data after jsonified, "+ result);

// remove item 
window.localStorage.removeItem("commodity");
var result = window.localStorage.getItem('commodity');
console.log("Data after removing the key "+ result);

//length
console.log("length of local storage " + window.localStorage.length);

// clear
window.localStorage.clear();
console.log("length of local storage - after clear " + window.localStorage.length);

When to use Local Storage

  1. Data stored in Local Storage can be easily accessed by third party individuals.
  2. So its important to know that any sensitive data must not sorted in Local Storage.
  3. Local Storage can help in storing temporary data before it is pushed to the server.
  4. Always clear local storage once the operation is completed.

Where the local storage is saved ?

Windows

  • Firefox: C:\Users\\AppData\Roaming\Mozilla\Firefox\Profiles\\webappsstore.sqlite, %APPDATA%\Mozilla\Firefox\Profiles\\webappsstore.sqlite
  • Chrome: %LocalAppData%\Google\Chrome\User Data\Default\Local Storage\

Linux

  • Firefox: ~/.mozilla/firefox//webappsstore.sqlite
  • Chrome: ~/.config/google-chrome/Default/Local Storage/

Mac

  • Firefox: ~/Library/Application Support/Firefox/Profiles//webappsstore.sqlite, ~/Library/Mozilla/Firefox/Profiles//webappsstore.sqlite
  • Chrome: ~/Library/Application Support/Google/Chrome//Local Storage/, ~/Library/Application Support/Google/Chrome/Default/Local Storage/

Downside of Localstorage

The majority of local storage’s drawbacks aren’t really significant. You may still not use it, but your app will run a little slower and you’ll experience a tiny developer inconvenience. Security, however, is distinct. Knowing and understanding the security model of local storage is crucial since it will have a significant impact on your website in ways you might not have anticipated.

Local storage also has the drawback of being insecure. In no way! Everyone who stores sensitive information in local storage, such as session data, user information, credit card information (even momentarily! ), and anything else you wouldn’t want shared publicly on social media, is doing it incorrectly.

The purpose of local storage in a browser for safe storage was not intended. It was intended to be a straightforward key/value store for strings only that programmers could use to create somewhat more complicated single page apps.

General Preventions

  1. For example, if we are using third party JavaScript libraries and they are injected with some scripts which extract the storage objects, our storage data won’t be secure anymore. Therefore it’s not recommended to save sensitive data as
    • Username/Password
    • Credit card info
    • JWT tokens
    • API keys
    • Personal info
    • Session ids
  2. Do not use the same origin for multiple web applications. Instead, use subdomains since otherwise, the storage will be shared with all. Reason is, for each subdomain it will have an unique localstorage; and they can’t communicate between subdomain instances.
  3. Once some data are stored in Local storage, the developers don’t have any control over it until the user clears it. If you want the data to be removed once the session ends, use SessionStorage.
  4. Validate, encode and escape data read from browser storage
  5. Encrypt data before saving

Why Skeleton Screens Improve Perceived Loading in Apps like LinkedIn

18 February 2025 at 11:55

Introduction

What do Reddit, Discord, Medium, and LinkedIn have in common? They use what’s called a skeleton loading screen for their applications. A skeleton screen is essentially a wireframe of the application. The wireframe is a placeholder until the application finally loads.

skeleton loader image

Rise of skeleton loader.

The term “skeleton screen” was introduced in 2013 by product designer Luke Wroblewski in a blog post about reducing perceived wait time. In this lukew.com/ff/entry.asp?1797 post, he explains how gradually revealing page content turns user attention to the content being loaded, and off of the loading time itself.

Skeleton Loader

Skeleton loading screens will improve your application’s user experience and make it feel more performant. The skeleton loading screen essentially impersonates the original layout.

This lets the user know what’s happening on the screen. The user interprets this as the application is booting up and the content is loading.

In simplest terms, Skeleton Loader is a static / animated placeholder for the information that is still loading. It mimic the structure and look of the entire view.

Why not just a loading spinner ?

Instead of showing a loading spinner, we could show a skeleton screen that makes the user see that there is progress happening when launching and navigating the application.

They let the user know that some content is loading and, more importantly, provide an indication of what is loading, whether it’s an image, text, card, and so on.

This gives the user the impression that the website is faster because they already know what type of content is loading before it appears. This is referred to as perceived performance.

Skeleton screens don’t really make pages load faster. Instead, they are designed to make it feel like pages are loading faster.

When to use ?

  1. Use on high-traffic pages where resources takes a bit long to load like account dashboard.
  2. When the component contains good amount of information, such as list or card.
  3. Could be replaced by spin in any situation, but can provide a better user experience.
  4. Use when there’s more than 1 element loading at the same time that requires an indicator.
  5. Use when you need to load multiple images at once, a skeleton screen might make a good placeholder. For these pages, consider implementing lazy loading first, which is a similar technique for decreasing perceived load time.

When not to use ?

  1. Not to use for a long-running process, e.g. importing data, manipulation of data etc. (Operations on data intensive applications)
  2. Not to use for fast processes that that take less than half a second.
  3. Users still associate video buffering with spinners. Avoid skeleton screens any time a video is loading on your page.
  4. For longer processes (uploads, download, file manipulation ) can use progress bar instead of skeleton loading.
  5. As a replacement for poor performance: If you can further optimize your website to actually load content more quickly, always pursue that first.

Let’s design a simple skeleton loading

index.html

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Skeleton Loading</title>

	<style>
		.card {
			width:  250px;
			height:  150px;
			background-color: #fff;
			padding: 10px;
			border-radius: 5px;
			border:  1px solid gray;
		}

		.card-skeleton {
			background-image: linear-gradient(90deg, #ccc, 0px, rgb(229 229 229 / 90%) 40px, #ccc 80px);
			background-size: 300%;
			background-position: 100% 0;
			border-radius: inherit;
			animation: shimmer 1.5s infinite;
		}

		.title {
			height: 15px;
			margin-bottom: 15px;
		}

		.description {
			height: 100px;
		}

		@keyframes shimmer{
			to {
				background-position: -100% 0;
			}
		}
	</style>

</head>
<body>
	<div class="card">
		<div class="card-skeleton title"></div>
		<div class="card-skeleton description"></div>
	</div>

</body>
</html>

Skeleton Loading .card { width: 250px; height: 150px; background-color: #fff; padding: 10px; border-radius: 5px; border: 1px solid gray; } .card-skeleton { background-image: linear-gradient(90deg, #ccc, 0px, rgb(229 229 229 / 90%) 40px, #ccc 80px); background-size: 300%; background-position: 100% 0; border-radius: inherit; animation: shimmer 1.5s infinite; } .title { height: 15px; margin-bottom: 15px; } .description { height: 100px; } @keyframes shimmer{ to { background-position: -100% 0; } }

Suggestions to keep in mind

  1. The goal is to design for a perception of decreased waiting time.
  2. Contents should replace skeleton exactly by position and size immediately after they are loaded.
  3. Using motion that moves from left to right (wave) gives a better perception of decreased waiting time than fading in and out (pulse).
  4. Using motion that is slow and steady gives a perception of decreased waiting time.

HAProxy EP 1: Traffic Police for Web

9 September 2024 at 16:59

In the world of web applications, imagine you’re running a very popular pizza place. Every evening, customers line up for a delicious slice of pizza. But if your single cashier can’t handle all the orders at once, customers might get frustrated and leave.

What if you could have a system that ensures every customer gets served quickly and efficiently? Enter HAProxy, a tool that helps manage and balance the flow of web traffic so that no single server gets overwhelmed.

Here’s a straightforward guide to understanding HAProxy, installing it, and setting it up to make your web application run smoothly.

What is HAProxy?

HAProxy stands for High Availability Proxy. It’s like a traffic director for your web traffic. It takes incoming requests (like people walking into your pizza place) and decides which server (or pizza station) should handle each request. This way, no single server gets too busy, and everything runs more efficiently.

Why Use HAProxy?

  • Handles More Traffic: Distributes incoming traffic across multiple servers so no single one gets overloaded.
  • Increases Reliability: If one server fails, HAProxy directs traffic to the remaining servers.
  • Improves Performance: Ensures that users get faster responses because the load is spread out.

Installing HAProxy

Here’s how you can install HAProxy on a Linux system:

  1. Open a Terminal: You’ll need to access your command line interface to install HAProxy.
  2. Install HAProxy: Type the following command and hit enter

sudo apt-get update
sudo apt-get install haproxy

3. Check Installation: Once installed, you can verify that HAProxy is running by typing


sudo systemctl status haproxy

This command shows you the current status of HAProxy, ensuring it’s up and running.

Configuring HAProxy

HAProxy’s configuration file is where you set up how it should handle incoming traffic. This file is usually located at /etc/haproxy/haproxy.cfg. Let’s break down the main parts of this configuration file,

1. The global Section

The global section is like setting the rules for the entire pizza place. It defines general settings for HAProxy itself, such as how it should operate, what kind of logging it should use, and what resources it needs. Here’s an example of what you might see in the global section


global
    log /dev/log local0
    log /dev/log local1 notice
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660
    user haproxy
    group haproxy
    daemon

Let’s break it down line by line:

  • log /dev/log local0: This line tells HAProxy to send log messages to the system log at /dev/log and to use the local0 logging facility. Logs help you keep track of what’s happening with HAProxy.
  • log /dev/log local1 notice: Similar to the previous line, but it uses the local1 logging facility and sets the log level to notice, which is a type of log message indicating important events.
  • chroot /var/lib/haproxy: This line tells HAProxy to run in a restricted area of the file system (/var/lib/haproxy). It’s a security measure to limit access to the rest of the system.
  • stats socket /run/haproxy/admin.sock mode 660: This sets up a special socket (a kind of communication endpoint) for administrative commands. The mode 660 part defines the permissions for this socket, allowing specific users to manage HAProxy.
  • user haproxy: Specifies that HAProxy should run as the user haproxy. Running as a specific user helps with security.
  • group haproxy: Similar to the user directive, this specifies that HAProxy should run under the haproxy group.
  • daemon: This tells HAProxy to run as a background service, rather than tying up a terminal window.

2. The defaults Section

The defaults section sets up default settings for HAProxy’s operation and is like defining standard procedures for the pizza place. It applies default configurations to both the frontend and backend sections unless overridden. Here’s an example of a defaults section


defaults
    log     global
    option  httplog
    option  dontlognull
    timeout connect 5000ms
    timeout client  50000ms
    timeout server  50000ms

Here’s what each line means:

  • log global: Tells HAProxy to use the logging settings defined in the global section for logging.
  • option httplog: Enables HTTP-specific logging. This means HAProxy will log details about HTTP requests and responses, which helps with troubleshooting and monitoring.
  • option dontlognull: Prevents logging of connections that don’t generate any data (null connections). This keeps the logs cleaner and more relevant.
  • timeout connect 5000ms: Sets the maximum time HAProxy will wait when trying to connect to a backend server to 5000 milliseconds (5 seconds). If the connection takes longer, it will be aborted.
  • timeout client 50000ms: Defines the maximum time HAProxy will wait for data from the client to 50000 milliseconds (50 seconds). If the client doesn’t send data within this time, the connection will be closed.
  • timeout server 50000ms: Similar to timeout client, but it sets the maximum time to wait for data from the server to 50000 milliseconds (50 seconds).

3. Frontend Section

The frontend section defines how HAProxy listens for incoming requests. Think of it as the entrance to your pizza place.


frontend http_front
    bind *:80
    default_backend http_back
  • frontend http_front: This is a name for your frontend configuration.
  • bind *:80: Tells HAProxy to listen for traffic on port 80 (the standard port for web traffic).
  • default_backend http_back: Specifies where the traffic should be sent (to the backend section).

4. Backend Section

The backend section describes where the traffic should be directed. Think of it as the different pizza stations where orders are processed.


backend http_back
    balance roundrobin
    server app1 192.168.1.2:5000 check
    server app2 192.168.1.3:5000 check
    server app3 192.168.1.4:5000 check
  • backend http_back: This is a name for your backend configuration.
  • balance roundrobin: Distributes traffic evenly across servers.
  • server app1 192.168.1.2:5000 check: Specifies a server (app1) at IP address 192.168.1.2 on port 5000. The check option ensures HAProxy checks if the server is healthy before sending traffic to it.
  • server app2 and server app3: Additional servers to handle traffic.

Testing Your Configuration

After setting up your configuration, you’ll need to restart HAProxy to apply the changes:


sudo systemctl restart haproxy

To check if everything is working, you can use a web browser or a tool like curl to send requests to HAProxy and see if it correctly distributes them across your servers.

Git

2 September 2024 at 13:32

Git is a powerful version control system which used to manage the code across multiple users and track changes across different versions.

Installation:

Download and install GIT from the below path

https://git-scm.com/download/win

Once installed, Git can be used as a version control system through various commands.
You can configure Git for a specific folder on your computer, allowing you to manage all changes to existing files and the addition of new files within that folder

Basic commands:

1. git init:

This will initialize new repository in the current directory. This also creates .git directory and store all version control information.

2. git config:
git config --global user.name "Ranjith "
git config --global user.mail "ranjith201099@gmail.com"
3. git status

Shows the current status of working area like staged, untracked and unstaged.

4. git add

add changes from working directory to the staging area, preparing them to commit.

To add specific file: git add "filename.py"
To add all changes git add .
5. git commit
git commit -m "<message>"

Commits the staged changes with descriptive mesage

6. git log

Displays the list of commit history for the repository.
It will show commit id, author, dates and commit changes
Creating a branch

git branch <branch_name> - to create branch
git checkout <branch_name> - to switch to the new branch
git branch -b <branch_name> 

to create and switch to branch
git branch - to view all the branches (current branch will be highlighted with asterisk)

Merge a branch:

Once completed work on a branch and want to integrate it into another branch (like master), merging comes to place.

It means all the changes we have made in <branch_name> will be merged with master branch.
First, switch to the branch you want to merge into: git checkout master
Then, use git merge <branch_name> to merge your branch.
Deleting branch
Once the code changes in <branch_name> merged into <master> branch, we might need to delete branch.
use git branch -d <branch_name> to delete branch

Image description

Image description

Js | Variable & Values |

29 August 2024 at 13:15

Jscript print :

console.log("Hello World ");

Variables & Values

Image description

Image description

  • The var keyword was used in all JavaScript code from 1995 to 2015.

  • The let and const keywords were added to JavaScript in 2015.

  • The var keyword should only be used in code written for older browsers.

Java script identifiers :

  • All JavaScript variables must be identified with unique names.

  • These unique names are called identifiers.

  • Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

  • The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs.

Names must begin with a letter.

Names can also begin with $ and (but we will not use it in this tutorial).

Names are case sensitive (y and Y are different variables).

Reserved words (like JavaScript keywords) cannot be used as names.

What is Good?

- let and const have block scope.

- let and const can not be redeclared.

- let and const must be declared before use.

- let and const does not bind to this.

- let and const are not hoisted.

What is Not Good?

- var does not have to be declared.

- var is hoisted.

- var binds to this.

Declare var variable :

var a; #Error undefined 

Initialize the variable :

var a = 10;

Redeclaration allowed :

var a = 100;
console.log(a);

Output :
100

Declare let variable :

let b;

Initialize the variable :

let b = 10;

Redeclaration is not allowed :

let b =100; 

Reassignment is allowed :

b = 200;
console.log(b);

cons must Declare & initialize 1st line :

const PI=31415 ;
//fixed Value Called Constant
console.log (PI);

Reassignment is not allowed :

const c = 1;
c = 2;
console.log(c);

Naming conventions :

correct way :

Correct camel Case convention :
let userName = 'John'; 
Underscore is not recommended but valid :

let user_Name ='Max'; 
start from Underscore :

let _userName ='Doe'; 

start from dollar symbol :

let $userName='Evo' ; 

string concatenate :

console.log('Welcome + userName);
console.log("Hi + userName);
console.log('Bye + userName);

Incorrect variable names :

Invalid: variable names cannot start with a number

let 5date= 5;

Resrved keywords (Functions):

let new = "data";
let function = 20;

Symbols in variable names :

let #function = 'data'; 
let @function = 'data';
let John&Jane = 'Friends'; 

let $function = 'data';  
#this one is correct

Scope of variables will on functions & loops :

var: Function scoped.
let: Block scoped.
const: Block scoped 
❌
❌