Skip to Content
Course content

204: Sharing Code Between Backend and Frontend with Scala.js

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I see this all the time when developers first dive into Scala.js: they assume that "sharing code" means they can just point their frontend project at their backend source folder and everything will magically work. They think, "I've already defined my User entity and my database logic in the backend; why write it again for the browser?"

The Fallacy: Sharing the Entire Domain Model

Here is where it falls apart. If you try to share your entire backend domain model—the classes that map directly to your database tables—you're going to hit a wall of compilation errors. Why? Because your backend User entity likely depends on Java-specific libraries, JDBC drivers, or Hibernate annotations. Scala.js cannot compile a Postgres driver to JavaScript. It simply doesn't exist in the browser environment.

If you try to force this, you'll spend your entire afternoon fighting ClassNotFoundException or weird linker errors. The mistake isn't the idea of sharing code; it's the scope of what you're sharing. You cannot share the implementation of your data persistence, but you absolutely should share the definition of your data contracts.

The Fix: The Pure Scala "Common" Module

The professional way to handle this is to create a third project in your build—usually called common or shared. This module must be "Pure Scala." No Java-only dependencies, no server-side frameworks, and no browser-specific DOM APIs. It's just logic and data.

Think of it as the "Source of Truth" for your API. Let's say we're building a shipping application. Instead of defining a ShippingAddress class in both the JVM and JS projects, we put it in common. But we don't stop at just data holders; we put the validation logic there too. This way, the frontend can tell the user their zip code is invalid instantly, and the backend can use the exact same code to reject the request if the frontend was bypassed.

// common/src/main/scala/com/app/models/Address.scala
package com.app.models

case class Address(
  street: String, 
  city: String, 
  zipCode: String
)

object Address {
  // This logic runs on BOTH the JVM and in the Browser
  def validate(addr: Address): Either[String, Address] = {
    if (addr.zipCode.length != 5) Left("Zip code must be exactly 5 digits")
    else if (addr.street.trim.isEmpty) Left("Street cannot be empty")
    else Right(addr)
  }
}

Now, in your backend (JVM), you import com.app.models.Address to handle the incoming JSON. In your frontend (Scala.js), you import the same class to bind to your form fields. I've found that this eliminates about 90% of the "out of sync" bugs where the backend expects a field that the frontend forgot to send.

One tip from the trenches: keep your common module lean. The moment you add a heavy library to it, you're increasing the bundle size of your JavaScript. If you need a complex library for validation on the backend, keep that in the JVM project and only share the basic case classes and simple logic in the common module.




📋 Practical Task

Build a Shared Product Validator for an E-Commerce Store

Your goal is to implement a shared validation layer to ensure a product's price and SKU are consistent across both the client and the server.

  • Part 1: The Common Module: Create a case class ProductRequest with fields for name: String, price: Double, and sku: String. Inside a companion object, implement a validate method that returns an Either[String, ProductRequest]. The validation should fail if:
    • The price is less than or equal to 0.
    • The SKU does not start with "PROD-".
  • Part 2: The Frontend Mock: Write a small Scala.js function that simulates a "Submit" button click. It should take a ProductRequest, run the shared validation, and print "Form Error: [message]" or "Sending to server..." to the console.
  • Part 3: The Backend Mock: Write a JVM function that simulates an API endpoint receiving a ProductRequest. It must run the same shared validation and return a 400 Bad Request message if it fails, ensuring the backend is not relying solely on the frontend's check.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.