<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Lakmal Asela</title>
    <description>The latest articles on DEV Community by Lakmal Asela (@lakmal_asela_8be4eb30d9db).</description>
    <link>https://dev.to/lakmal_asela_8be4eb30d9db</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1591529%2Fbf9e65b5-55f1-48f2-a78d-bd547fde73fc.jpg</url>
      <title>DEV Community: Lakmal Asela</title>
      <link>https://dev.to/lakmal_asela_8be4eb30d9db</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/lakmal_asela_8be4eb30d9db"/>
    <language>en</language>
    <item>
      <title>Understanding Passport &amp; OAuth Authentication</title>
      <dc:creator>Lakmal Asela</dc:creator>
      <pubDate>Sun, 27 Apr 2025 06:08:34 +0000</pubDate>
      <link>https://dev.to/lakmal_asela_8be4eb30d9db/understanding-passport-oauth-authentication-4f8a</link>
      <guid>https://dev.to/lakmal_asela_8be4eb30d9db/understanding-passport-oauth-authentication-4f8a</guid>
      <description>&lt;h2&gt;
  
  
  What is Authentication?
&lt;/h2&gt;

&lt;p&gt;Authentication is the act of figuring out who a user is.&lt;br&gt;
Example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You do username/password login to a website.&lt;/li&gt;
&lt;li&gt;Website figures out if you are really a user.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  What is Passport?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Passport is a Node.js middleware.&lt;/li&gt;
&lt;li&gt;It helps deliver authentication (login mechanisms).&lt;/li&gt;
&lt;li&gt;It's extremely flexible and modular.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Key Features of Passport:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Minimalistic: Not going to force you to do things a certain way.&lt;/li&gt;
&lt;li&gt;Has support for over 500 strategies (username/password, Google, Facebook, etc.).&lt;/li&gt;
&lt;li&gt;Works perfectly with Express, NestJS, and most Node.js frameworks.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Remember: Passport DOESN'T handle sessions, cookies, or databases itself. You write that code yourself if needed.&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  What is a Strategy in Passport?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;A Strategy is a Passport plugin.&lt;/li&gt;
&lt;li&gt;It defines how you want to authenticate users.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Examples of Strategies:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;passport-local: Login with username + password&lt;/li&gt;
&lt;li&gt;passport-jwt: Login with JWT tokens&lt;/li&gt;
&lt;li&gt;passport-google-oauth20: Login with Google account&lt;/li&gt;
&lt;li&gt;passport-facebook: Login with Facebook&lt;/li&gt;
&lt;li&gt;You can use more than one strategy in the same project!&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  What is OAuth?
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;OAuth (Open Authorization) is an open authorization standard protocol.&lt;/li&gt;
&lt;li&gt;It allows users to share access to their data without giving out passwords.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Example:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;You click "Login with Google" =&amp;gt; Google asks for permission =&amp;gt; You authorize =&amp;gt; Site gets your email/profile.&lt;/strong&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  How OAuth2 Works (Flow)
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;User clicks "Login with Google".&lt;/li&gt;
&lt;li&gt;Client App (your app) redirects user to Google's login page.&lt;/li&gt;
&lt;li&gt;User logs in on Google and grants permission.&lt;/li&gt;
&lt;li&gt;Google sends an authorization code back to your app.&lt;/li&gt;
&lt;li&gt;Your app exchanges that code for an access token.&lt;/li&gt;
&lt;li&gt;Your app uses the access token to get user info (email, name, etc.).&lt;/li&gt;
&lt;li&gt;Your app logs in the user.&lt;/li&gt;
&lt;/ol&gt;

&lt;ul&gt;
&lt;li&gt;This keeps the user's password secure.&lt;/li&gt;
&lt;li&gt;Only tokens are exchanged, not passwords.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Passport + OAuth + NestJS Flow
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Install Passport&lt;/li&gt;
&lt;li&gt;Install OAuth Strategy (like passport-google-oauth20)&lt;/li&gt;
&lt;li&gt;Setup a strategy&lt;/li&gt;
&lt;li&gt;Setup routes for login and callback&lt;/li&gt;
&lt;li&gt;Extract user info after successful login&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Practical Example: Google OAuth with NestJS
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Install Required Packages&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install @nestjs/passport passport passport-google-oauth20
npm install @nestjs/jwt passport-jwt
npm install @types/passport-google-oauth20 --save-dev

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Create the Google Strategy&lt;/strong&gt;&lt;br&gt;
src/auth/google.strategy.ts&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, VerifyCallback } from 'passport-google-oauth20';

@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
  constructor() {
    super({
      clientID: 'YOUR_GOOGLE_CLIENT_ID',  // ←replace with your credentials
      clientSecret: 'YOUR_GOOGLE_CLIENT_SECRET', // ← replace with your credentials
      callbackURL: 'http://localhost:3000/auth/google/callback',
      scope: ['email', 'profile'],
    });
  }

  async validate(accessToken: string, refreshToken: string, profile: any, done: VerifyCallback): Promise&amp;lt;any&amp;gt; {
    const { name, emails, photos } = profile;
    const user = {
      email: emails[0].value,
      firstName: name.givenName,
      lastName: name.familyName,
      picture: photos[0].value,
      accessToken,
    };
    done(null, user);
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Create Auth Controller&lt;/strong&gt;&lt;br&gt;
src/auth/auth.controller.ts&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Controller, Get, Req, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller('auth')
export class AuthController {

  @Get('google')
  @UseGuards(AuthGuard('google'))
  async googleAuth(@Req() req) {
    // This route will redirect user to Google login
  }

  @Get('google/callback')
  @UseGuards(AuthGuard('google'))
  async googleAuthRedirect(@Req() req) {
    // This route is hit after login success
    return {
      message: 'User information from Google',
      user: req.user,
    };
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4: Create Auth Module&lt;/strong&gt;&lt;br&gt;
src/auth/auth.module.ts&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { GoogleStrategy } from './google.strategy';

@Module({
  controllers: [AuthController],
  providers: [GoogleStrategy],
})
export class AuthModule {}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 5: Import AuthModule in App Module&lt;/strong&gt;&lt;br&gt;
src/app.module.ts&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Module } from '@nestjs/common';
import { AuthModule } from './auth/auth.module';

@Module({
  imports: [AuthModule],
})
export class AppModule {}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  How It Works Now:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Open browser =&amp;gt; &lt;a href="http://localhost:3000/auth/google" rel="noopener noreferrer"&gt;http://localhost:3000/auth/google&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;You get redirected to Google Login page.&lt;/li&gt;
&lt;li&gt;After login =&amp;gt; Google redirects to &lt;a href="http://localhost:3000/auth/google/callback" rel="noopener noreferrer"&gt;http://localhost:3000/auth/google/callback&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Your user information (email, name, photo) is read by the app.&lt;/li&gt;
&lt;li&gt;User can be saved in database, session can be created, or JWT can be created here.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Concept Meaning
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Passport Middleware to make authentication easier&lt;/li&gt;
&lt;li&gt;OAuth&lt;/li&gt;
&lt;li&gt;Protocol to allow login via third parties like Google, Facebook&lt;/li&gt;
&lt;li&gt;Strategy&lt;/li&gt;
&lt;li&gt;Plugin (e.g.: GoogleStrategy) to handle specific login method&lt;/li&gt;
&lt;li&gt;NestJS Integration&lt;/li&gt;
&lt;li&gt;You implement Guards and Strategies for redirection and login&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Final Key Points
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Never make your Google client secret public.&lt;/li&gt;
&lt;li&gt;Use environment variables (.env file) for secret credentials.&lt;/li&gt;
&lt;li&gt;You can also extend the same for Facebook, Github, LinkedIn by just changing the strategy.&lt;/li&gt;
&lt;li&gt;Once OAuth login is done, generally you generate your own JWT token to manage user sessions.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  If you want, after this you can:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Automatically save user information to your database after login.&lt;/li&gt;
&lt;li&gt;Issue your own JWT tokens following an OAuth login.&lt;/li&gt;
&lt;li&gt;Protect specific routes so that only authenticated users can access them.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>oauth</category>
      <category>passport</category>
      <category>nextjs</category>
      <category>jwt</category>
    </item>
    <item>
      <title>DTO vs Entity: Why You Should Separate Concerns</title>
      <dc:creator>Lakmal Asela</dc:creator>
      <pubDate>Sat, 28 Dec 2024 04:14:56 +0000</pubDate>
      <link>https://dev.to/lakmal_asela_8be4eb30d9db/dto-vs-entity-why-you-should-separate-concerns-15jd</link>
      <guid>https://dev.to/lakmal_asela_8be4eb30d9db/dto-vs-entity-why-you-should-separate-concerns-15jd</guid>
      <description>&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The Data Transfer Object is a design pattern used to transfer data across different layers or components of an application. It is a simple, flat, serializable object that contains only fields and accessors-appropriately getters and setters-without business logic. The main role of DTOs is to enable the effective encapsulation and transfer of data.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Clean and maintainable code is the key to modern software development for scalable and efficient applications. In any ordinary application, two very commonly used concepts, Data Transfer Objects and Entities, play an important role in segregating the concerns within an application. This article will explain the differences between Data Transfer Objects and Entities, why separating their responsibilities is important, and how to implement them.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is an Entity?
&lt;/h2&gt;

&lt;p&gt;An Entity represents a real-world object or concept in the domain of your application. It directly maps onto the database table and contains the business logic associated with that object. These are typically part of a persistence layer and are managed by an ORM framework like Hibernate or JPA in Java.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String email;

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Key Characteristics of Entities:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Mapped directly to a database table.&lt;/li&gt;
&lt;li&gt;Contains both data and business logic.&lt;/li&gt;
&lt;li&gt;Changes in the database structure can directly impact entities.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What is a DTO?
&lt;/h2&gt;

&lt;p&gt;A Data Transfer Object, or DTO, is just a simple, flat object used to transfer data between different layers of an application-from the backend to the frontend, for example. It is designed to carry data but not business logic. They are used to shape the data according to the specific requirements of a certain use case or API endpoint.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserDTO {

    @NotNull(message = "Name is required")
    private String name;
    @NotNull(message = "Email is required")
    private String email;

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Key Characteristics of DTOs:
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Do not map directly to database tables.&lt;/li&gt;
&lt;li&gt;Used for transferring data, especially between layers or across networks (e.g., APIs).&lt;/li&gt;
&lt;li&gt;Contains only fields, getters, and setters (no business logic).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Why Separate DTOs and Entities?
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1. Encapsulation and Security&lt;/strong&gt;&lt;br&gt;
Entities often contain sensitive information-for example, password, internal IDs-that you do not want to expose to external clients or other layers of the application.&lt;br&gt;
Using DTOs enables you to control what data gets exposed and the structure of the data.&lt;br&gt;
&lt;strong&gt;2. Decoupling Layers&lt;/strong&gt;&lt;br&gt;
DTO is a bridge between layers like service layer and API layer, that decouples each of them; in case some layer faces changes, for example, database schema changes, the other layer wouldn't be affected.&lt;br&gt;
Assume there's some kind of change in your database structure, your DTO might remain unchanged because of that it saves your API from breaking changes.&lt;br&gt;
&lt;strong&gt;3. Use Case Customization&lt;/strong&gt;&lt;br&gt;
DTOs allow the developer to adapt the structure of the data to his needs. For instance, you might want to return only the name and email fields for a user, while you would exclude fields like id and password from the return.&lt;br&gt;
&lt;strong&gt;4. Performance Optimization&lt;/strong&gt;&lt;br&gt;
By including only the necessary fields, DTOs reduce the size of the data transferred over the network, improving performance in distributed systems, such as REST APIs.&lt;br&gt;
&lt;strong&gt;5. Testability and Maintainability&lt;/strong&gt;&lt;br&gt;
DTOs make unit testing more straightforward and easy since they are simple and independent of any persistence layer dependencies.&lt;br&gt;
DTOs also make the code base more maintainable due to a separation of concerns.&lt;br&gt;
&lt;strong&gt;6. Avoids Tight Coupling&lt;/strong&gt;&lt;br&gt;
The approach of using entities directly inside APIs tightly couples your persistence model with your API contract. Changes in the entity structure may inadvertently break API consumers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Service Layer with Mapping
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
public class UserMapper {
    public static UserDTO toDTO(User user) {
        UserDTO dto = new UserDTO();
        dto.setName(user.getName());
        dto.setEmail(user.getEmail());
        return dto;
    }

    public static User toEntity(UserDTO dto) {
        User user = new User();
        user.setName(dto.getName());
        user.setEmail(dto.getEmail());
        return user;
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Service Example:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public UserDTO getUserById(Long id) {
        User user = userRepository.findById(id).orElseThrow(() -&amp;gt; new RuntimeException("User not found"));
        return UserMapper.toDTO(user);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Best Practices of Using DTOs and Entities
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Never Expose the Entities in APIs:&lt;/strong&gt;&lt;br&gt;
Always map the entities to DTOs before returning data to the external client.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Using Libraries for Mapping:&lt;/strong&gt;&lt;br&gt;
These tools, like MapStruct or ModelMapper, enable ease of mapping between DTOs and Entities and reduce boilerplate code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Keep DTOs Simple:&lt;/strong&gt;&lt;br&gt;
Don't add business logic or complicated behavior to your DTOs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use Validation in DTOs:&lt;/strong&gt;&lt;br&gt;
Let validation of the incoming data at DTO level be done with the use of annotations such as @Size and &lt;a class="mentioned-user" href="https://dev.to/notblank"&gt;@notblank&lt;/a&gt; beforehand and map it to an entity.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Create Different DTOs for Different Use Cases:&lt;/strong&gt;&lt;br&gt;
You could have a UserResponseDTO for API responses, a UserCreateRequestDTO in cases of handling user creation requests.&lt;/p&gt;

&lt;h2&gt;
  
  
  Summary of DTO
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;The separation of DTOs from entities keeps the code base clean and maintainable, decouples the concerns, enhances security, and ensures performance. While entities will care about the business logic and database interaction logic, DTOs know only about the data transfer between layers or systems. The separation of these elements follows best practices in software design and protects your application from unexpected side effects of tightly coupled components.&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>dto</category>
      <category>springboot</category>
      <category>entity</category>
    </item>
    <item>
      <title>What is the CORS ?</title>
      <dc:creator>Lakmal Asela</dc:creator>
      <pubDate>Mon, 16 Sep 2024 09:40:36 +0000</pubDate>
      <link>https://dev.to/lakmal_asela_8be4eb30d9db/what-is-the-cors--1eam</link>
      <guid>https://dev.to/lakmal_asela_8be4eb30d9db/what-is-the-cors--1eam</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;CORS- Cross-Origin Resource Sharing-is a security feature used by web browsers. This feature stops a web page from requesting resources, or data, from a domain different from the one that served the web page. It is done to protect the users by disallowing malicious sites from sending unauthorized requests to servers or APIs at other domains.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fci1my8sovivdr96fvlh8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fci1my8sovivdr96fvlh8.png" alt="Image description" width="800" height="269"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  How CORS Works
&lt;/h2&gt;

&lt;p&gt;When a web page, in a certain origin, sends a request to a different origin, the browser first checks if the server allows this kind of cross-origin request. If it isn't so configured, the browser blocks the request. CORS defines a way in which a server can safely handle these cross-origin requests.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;&lt;strong&gt;CORS relies on HTTP headers to let the server inform the browser whether or not the request is allowed. The key headers include:&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Access-Control-Allow-Origin: Specifies which origin(s) are allowed to make requests (e.g., a specific domain or * for any domain).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Access-Control-Allow-Methods: Specifies which HTTP methods (e.g., GET, POST) are allowed.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Access-Control-Allow-Headers: Specifies which headers can be included in the request.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Access-Control-Allow-Credentials: Indicates whether credentials like cookies or authorization headers are allowed to be sent.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Why CORS is Used
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Security&lt;/strong&gt;: This is one of the most important features. It makes sure that there aren't any unauthorized requests allowed between different sites. A script originating from one domain is not allowed to access resources from another domain unless explicitly allowed.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Controlled Sharing&lt;/strong&gt;: This is a controlled exposure to resources from other origins, notably in cases when APIs or services are consumed by applications hosted over different domains.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  CORS Implementation in Spring Boot
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Global Configuration&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package com.logmaven.exmaven.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // Allowing CORS requests from http://localhost:3000
        registry.addMapping("/**")  // Apply to all endpoints
                .allowedOrigins("http://localhost:3000")  // Allow requests from this origin
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")  // Allow these HTTP methods
                .allowedHeaders("*")  // Allow all headers
                .allowCredentials(true);  // Allow credentials like cookies
    }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;CORS Configuration Using Spring Security&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@EnableWebSecurity
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable() // Enable CORS and disable CSRF for simplicity
            .authorizeRequests()
            .anyRequest().authenticated(); // Allow only authenticated requests
        return http.build();
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:3000");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;This configuration enables CORS for all endpoints, allowing requests from &lt;a href="http://localhost:3000" rel="noopener noreferrer"&gt;http://localhost:3000&lt;/a&gt;. You can adjust it to your specific requirements, including credentials, headers, and allowed HTTP methods.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Advantages of CORS
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Security Control: Prevents unauthorized cross-origin requests.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Granular Access: Allows fine-grained access to resources based on origin, methods, and headers.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Interoperability: This allows modern web applications to securely consume APIs and services from different origins.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>cors</category>
      <category>java</category>
      <category>springboot</category>
      <category>springsecurity</category>
    </item>
    <item>
      <title>JavaScript Event Loop</title>
      <dc:creator>Lakmal Asela</dc:creator>
      <pubDate>Tue, 27 Aug 2024 08:53:59 +0000</pubDate>
      <link>https://dev.to/lakmal_asela_8be4eb30d9db/javascript-event-loop-1oed</link>
      <guid>https://dev.to/lakmal_asela_8be4eb30d9db/javascript-event-loop-1oed</guid>
      <description>&lt;p&gt;&lt;strong&gt;What is the JavaScript Event Loop?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In JavaScript, an event loop is a mechanism that controls the execution of code, events, or messages using non-blocking I/O. This provides a way for non-blocking, or asynchronous, operations in JavaScript.&lt;/p&gt;

&lt;blockquote&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Key Concepts
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;1.Single Threaded&lt;/strong&gt;&lt;br&gt;
JavaScript is single-threaded, which means it executes one task at a time. Single threaded, therefore, one thread on which JavaScript executes is the so-called "main thread.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2.Call Stack&lt;/strong&gt;&lt;br&gt;
It is the data structure in which JavaScript keeps track of function calls. A function call is pushed onto the stack. When it returns, it is removed. When it is empty, JavaScript is ready to process the next thing. It is also commonly referred to as the "main thread".&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3.Heap&lt;/strong&gt;&lt;br&gt;
This is where JavaScript stores objects and variables. It's used for dynamic memory allocation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4.Event Queue&lt;/strong&gt;&lt;br&gt;
A queue of messages or tasks that are waiting to get executed. When a task is added into the queue, it waits for the call stack to be empty to execute.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5.Event Loop&lt;/strong&gt;&lt;br&gt;
It is something that constantly monitors the call stack and event queue. If the call stack is empty, it then moves tasks from the event queue into the call stack and executes them. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxloscx9i092gbmcehamf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxloscx9i092gbmcehamf.png" alt="Image description" width="800" height="319"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Process&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Execution of Code: When JavaScript starts to execute code, it pushes the function calls onto the call stack. Additionally, it executes one function after another.&lt;/li&gt;
&lt;li&gt;Asynchronous Operations: Immediately an operation is asynchronous, like a setTimeout or a network request, the JavaScript does not block the execution. Instead, it forwards that operation to Web APIs, say to the browser's timer or to services handling HTTP requests.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Callback Functions: When an asynchronous operation completes, its callback function is pushed into the event queue.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Event Loop Checking: Event Loop now checks the call stack as well as the event queue in the order. If the call stack is empty, it picks the first task from the event queue and pushes that into the call stack to run it.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log('Start');

setTimeout(() =&amp;gt; {
  console.log('Timeout 1');
}, 1000);

setTimeout(() =&amp;gt; {
  console.log('Timeout 2');
}, 500);

console.log('End');

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Note that the following will occur step-by-step:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Since start is a synchronous operation, it's logged immediately.&lt;/li&gt;
&lt;li&gt;The first setTimeout is registered with 1000ms delay and then goes to the Web APIs. Its callback will be put in the event queue after 1000ms.&lt;/li&gt;
&lt;li&gt;The second setTimeout is registered with 500ms delay and then goes to the Web APIs. Its callback will be put in the event queue after 500ms.&lt;/li&gt;
&lt;li&gt;End is loged right away because it's synchronous.&lt;/li&gt;
&lt;li&gt;In 500ms, the callback for the second setTimeout moves from the event queue to the call stack and logs Timeout 2.&lt;/li&gt;
&lt;li&gt;The first rate for setTimeout undergoes from the event queue to the call stack in 1000ms and log Timeout 1.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Summary&lt;/strong&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Call Stack: Executes functions in order.&lt;/li&gt;
&lt;li&gt;Event Queue: Stores messages or tasks to be executed.&lt;/li&gt;
&lt;li&gt;Event Loop: It executes the tasks, which are passed from the event queue into the call stack when it's empty.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>javascript</category>
      <category>eventloop</category>
      <category>asynchronous</category>
    </item>
    <item>
      <title>JavaScript Date prototype Property</title>
      <dc:creator>Lakmal Asela</dc:creator>
      <pubDate>Mon, 29 Jul 2024 00:27:42 +0000</pubDate>
      <link>https://dev.to/lakmal_asela_8be4eb30d9db/javascript-date-prototype-property-5f17</link>
      <guid>https://dev.to/lakmal_asela_8be4eb30d9db/javascript-date-prototype-property-5f17</guid>
      <description>&lt;p&gt;The Date.prototype object in JavaScript is used to extend or override the behavior of Date instances. This provides a means of adding custom methods and properties to all Date objects.&lt;/p&gt;

&lt;h2&gt;
  
  
  Extending Date with Custom Methods
&lt;/h2&gt;

&lt;p&gt;You can add custom methods to Date.prototype to make them available on all instances of Date. For example, you may want to add a method that returns the number of total days.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Date.prototype.daysFromStartOfYear = function() {&lt;br&gt;
    const startOfYear = new Date(this.getFullYear(), 0, 1); // January 1st of the current year&lt;br&gt;
    const oneDay = 24 * 60 * 60 * 1000; // Milliseconds in one day&lt;br&gt;
    const differenceInTime = this.getTime() - startOfYear.getTime();&lt;br&gt;
    return Math.floor(differenceInTime / oneDay) + 1; // Add 1 to include the start day&lt;br&gt;
}&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Explanation&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;Date.prototype.daysFromStartOfYear&lt;/code&gt;: Defines a new method daysFromStartOfYear on the Date prototype, making it available to all Date instances.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;new Date(this.getFullYear(), 0, 1)&lt;/code&gt;: Creates a Date object for January 1st of the current year (this.getFullYear()).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;this.getTime() - startOfYear.getTime()&lt;/code&gt;: Calculates the difference in milliseconds between the current date (this) and January 1st of the year.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;Math.floor(differenceInTime / oneDay) + 1&lt;/code&gt;: Converts milliseconds to days. Adding 1 ensures that January 1st is counted as day 1.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This solution won't modify the Date.prototype object, and in some cases, may be useful when you need to apply the method and not affect all instances of Date&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Array Loops in JavaScript</title>
      <dc:creator>Lakmal Asela</dc:creator>
      <pubDate>Sat, 20 Jul 2024 05:04:49 +0000</pubDate>
      <link>https://dev.to/lakmal_asela_8be4eb30d9db/array-loops-in-javascript-27j2</link>
      <guid>https://dev.to/lakmal_asela_8be4eb30d9db/array-loops-in-javascript-27j2</guid>
      <description>&lt;p&gt;&lt;strong&gt;Ever find yourself bogged down by writing repetitive loops to manipulate arrays?&lt;br&gt;
JavaScript has a hidden arsenal: a set of powerful array methods like map, filter, and many others!&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;These methods simplify array manipulation, making your code cleaner, more concise, and much more enjoyable to write.&lt;br&gt;
Let's dive into some of these gems:&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;️&lt;strong&gt;Map Method&lt;/strong&gt;: Transform each element in an array effortlessly (pass in a function to alter them).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Filter Method&lt;/strong&gt;: Streamline your array with ease (create a new array with elements that satisfy your criteria).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Find Method&lt;/strong&gt;: Act like a detective ️‍(locate the first element that meets your condition).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;FindIndex Method&lt;/strong&gt;: Sharpen your investigative skills (find the index of the first matching element).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Fill Method&lt;/strong&gt;: Repaint your array with new values (fill the entire array or just a specific range).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Some Method&lt;/strong&gt;: Unleash your inner Sherlock (check if at least one element fulfills a condition).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flk236qcsiwie1o79rn58.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flk236qcsiwie1o79rn58.gif" alt="Image description" width="1024" height="1024"&gt;&lt;/a&gt;**: &lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>es6</category>
    </item>
    <item>
      <title>Connection Pooling in Spring Boot</title>
      <dc:creator>Lakmal Asela</dc:creator>
      <pubDate>Fri, 07 Jun 2024 15:46:59 +0000</pubDate>
      <link>https://dev.to/lakmal_asela_8be4eb30d9db/connection-pooling-in-spring-boot-4k21</link>
      <guid>https://dev.to/lakmal_asela_8be4eb30d9db/connection-pooling-in-spring-boot-4k21</guid>
      <description>&lt;p&gt;connection pooling is a method specifically designed to manage and reuse database connections, enhancing the performance of applications that interact with databases.&lt;br&gt;
A database connection acts as a bridge between a Java application and a database server. Establishing and terminating these connections should be making efficient management crucial for optimal application performance.&lt;br&gt;
&lt;strong&gt;Connection pooling&lt;/strong&gt; involves creating a pre-established database connections that can be reused. This is contributes reduces the overhead of establishing new connections for each database operation, thereby enhancing application efficiency &amp;amp; concurrency controlling.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fia6olrnk8h38eocmel17.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fia6olrnk8h38eocmel17.png" alt="Image description" width="501" height="321"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Without connection pooling, database interaction would require establishing a new connection and terminating it afterward. This repetitive task &amp;amp; occur the overhead, leading to additionally effort to potential resource drain. Connection pooling resolve these issues by reusing existing connections &amp;amp; it will be in improved efficiency, concurrency, and overall system stability.&lt;/p&gt;

&lt;p&gt;The Spring boot introduce the HikariCP for connection pool implementation. &lt;/p&gt;

&lt;p&gt;HikariCP can configure in your application.properties file&lt;/p&gt;

&lt;p&gt;&lt;code&gt;# HikariCP settings&lt;br&gt;
spring.datasource.hikari.maximum-pool-size=10&lt;br&gt;
spring.datasource.hikari.minimum-idle=5&lt;br&gt;
spring.datasource.hikari.idle-timeout=600000&lt;br&gt;
spring.datasource.hikari.connection-timeout=30000&lt;br&gt;
spring.datasource.hikari.max-lifetime=1800000&lt;br&gt;
spring.datasource.hikari.leak-detection-threshold=2000&lt;br&gt;
spring.datasource.hikari.pool-name=MyHikariCP&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Summery&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Connection pooling is a vital mechanism for enhancing the performance and scalability of applications that interact with databases. By maintaining a pool of reusable database connections, connection pooling minimizes the overhead associated with establishing and tearing down connections for each database operation. This approach not only optimizes resource utilization but also improves application responsiveness and stability.&lt;/p&gt;

</description>
      <category>springboot</category>
      <category>database</category>
      <category>connectionpooling</category>
    </item>
  </channel>
</rss>
