DEV Community

Switch by Skill
Switch by Skill

Posted on Originally published at switchbyskill.com

Spring Boot developer learning Express: what carries over, what's new, 30-day plan

What carries over

Spring Boot concept Express equivalent How it helps you transition
Dependency injection (DI) – Spring’s @Autowired and component scanning Manual wiring or lightweight DI libraries (e.g., awilix, inversify) You already think in terms of loosely‑coupled services; you can keep that mindset and introduce a DI container when the app grows.
Configuration properties – application.yml / @Value Environment variables & dotenv or config package The idea of externalising config stays the same; just read process.env or a JSON/YAML config file.
Profiles / environments – @Profile("dev") NODE_ENV and separate config files (config/default.json, config/production.json) You’ll still switch behaviour based on environment, only the mechanism changes.
REST controller annotations – @RestController, @GetMapping Route handlers – app.get('/', fn) The mapping of HTTP verbs to functions is identical; you just write the function inline or import a router module.
Exception handling – @ControllerAdvice Error‑handling middleware – app.use((err, req, res, next) => …) Centralised error handling is still a best practice; just use a middleware function with four arguments.
Embedded server – Spring Boot ships Tomcat/Jetty Node’s built‑in HTTP server – Express starts its own listener You no longer configure a servlet container; you call app.listen(port).
Testing support – @SpringBootTest, MockMvc SuperTest + Jest/Mocha The test‑first mindset transfers; you’ll spin up the Express app in memory and issue HTTP calls.
Logging abstraction – org.slf4j.Logger Winston / Pino Structured logging stays important; just swap the logger implementation.
Validation annotations – @Valid, @NotNull Joi / express‑validator Validation is still declarative; you just use a different library.
Security filters – OncePerRequestFilter Middleware – app.use(authMiddleware) The filter chain concept is identical; you write a function that runs before the route handler.

The mental models you already own—layered architecture, externalised configuration, test‑driven development—are all still valid. The main shift is from a convention‑heavy, annotation‑driven Java world to a more explicit, code‑centric JavaScript environment.


What's new

Side‑by‑side example: a simple “Hello, World” endpoint that returns JSON

Spring Boot (Java)

package com.example.demo;

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*;

@RestController
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @GetMapping("/greet")
    public Greeting greet(@RequestParam(defaultValue = "World") String name) {
        return new Greeting("Hello, " + name + "!");
    }

    static class Greeting {
        private final String message;
        public Greeting(String message) { this.message = message; }
        public String getMessage() { return message; }
    }
}
Enter fullscreen mode Exit fullscreen mode

Express (Node.js)

// app.js
const express = require('express');
const app = express();

app.get('/greet', (req, res) => {
  const name = req.query.name || 'World';
  res.json({ message: `Hello, ${name}!` });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server listening on ${PORT}`));
Enter fullscreen mode Exit fullscreen mode

What changed and why

Aspect Spring Boot Express
Project bootstrap spring init creates a Maven/Gradle project with a pom.xml or build.gradle. npm init -y creates a package.json; then npm install express.
Entry point public static void main runs the embedded servlet container. app.listen starts the Node event loop; no separate container.
Routing syntax Annotations (@GetMapping) on methods; path variables are bound automatically. Functions (app.get(path, handler)) receive req and res objects; you manually read query params.
Response building Return a POJO; Spring serialises to JSON via Jackson. Call res.json with a plain object; Express uses JSON.stringify.
Type safety Compile‑time Java types; IDE can infer DTO shape. JavaScript is dynamically typed; you may add TypeScript later for similar safety.
Dependency management Maven/Gradle resolves JARs from Maven Central. npm resolves packages from the npm registry.
Configuration application.yml → @Value. .env or config/*.json → process.env.
Build & run ./mvnw spring-boot:run or java -jar. node app.js (or npm start).

Express gives you full control over the request‑response cycle with far fewer layers. That freedom is powerful but also means you must decide on conventions (folder layout, error handling, validation) that Spring Boot supplies out of the box.


Common pitfalls

  1. Blocking the event loop – In Java you’re used to multi‑threaded blocking I/O. In Node a single thread handles all requests; any synchronous file read, heavy computation, or long‑running loop will stall the whole server. Use async APIs (fs.promises, await) or off‑load CPU‑heavy work to worker threads.

  2. Missing next() in middleware – Forgetting to call next() (or to end the response) leaves the request hanging. Always end the chain with res.send/... or next(err) for errors.

  3. Improper error propagation – Throwing inside an async route handler won’t be caught by Express automatically. Wrap async handlers with a helper (asyncHandler(fn)) or use express-async-errors.

  4. Over‑reliance on require order – Circular require statements can produce partially initialised modules. Keep module boundaries clean; consider using ES modules (import) when possible.

  5. Configuration drift – Mixing environment variables with hard‑coded values leads to “works on my machine”. Centralise config with a library (dotenv, config) and validate at startup.

  6. Ignoring security headers – Spring Security adds many defaults (CSRF, X‑XSS‑Protection). In Express you must add them manually (helmet, CORS config).

  7. Testing without isolation – Starting the real server in every test slows the suite. Export the Express app object (module.exports = app) and let SuperTest inject requests without listening on a port.

  8. Logging to console only – System.out.println is rare in Spring Boot; you use SLF4J. In Express, console.log is fine for dev but replace it with a structured logger (Winston, Pino) for production.

  9. Neglecting graceful shutdown – Spring Boot handles SIGTERM and drains connections. In Node you must listen for process.on('SIGTERM') and close the server, then exit.

  10. Assuming the same DI pattern – Spring’s container resolves dependencies automatically. In Express you either wire manually or adopt a DI library; mixing the two approaches can cause confusion.


Your 30‑day plan

Week 1 – Foundations

  1. Set up the tooling – Install Node ≥ 18, npm, and VS Code (or your preferred IDE). Run npm init -y and npm install express.
  2. Create a minimal project – Scaffold app.js with a “Hello, World” route, add a start script in package.json, and run npm start.
  3. Explore the request/response objects – Log req.method, req.path, req.headers, and experiment with res.status, res.json, res.sendFile.
  4. Small project – Build a Todo API with in‑memory storage (GET /todos, POST /todos, DELETE /todos/:id). No database yet; focus on routing and JSON handling.

Week 2 – Structure & Middleware

  1. Introduce routers – Move the Todo routes into routes/todo.js and mount with app.use('/api', todoRouter).
  2. Add middleware – Implement request logging (morgan), body parsing (express.json()), and a simple auth stub (app.use(authMiddleware)).
  3. Error handling – Write a centralized error‑handling middleware that formats errors as { error: message, code }.
  4. Small project – Extend the Todo API to include validation with express-validator (e.g., title must be non‑empty). Write unit tests with Jest and SuperTest.

Week 3 – Persistence & Configuration

  1. Pick a data store – Install mongoose (MongoDB) or pg (PostgreSQL) and create a simple model for Todo items.
  2. Externalise configuration – Add dotenv and a config/default.json file; read DB connection string from process.env.
  3. Introduce async/await – Refactor all route handlers to use async functions; wrap them with an asyncHandler helper to forward errors.
  4. Small project – Convert the in‑memory Todo API to use the chosen database. Add a migration script (npm run migrate) if using PostgreSQL.

Week 4 – Production readiness & Polish

  1. Security hardening – Install helmet, configure CORS (cors package), and add rate limiting (express-rate-limit).
  2. Logging – Replace console.log with pino (or winston), output JSON logs, and add request‑id correlation (cls-hooked or pino-http).
  3. Graceful shutdown – Listen for SIGINT/SIGTERM, close the HTTP server and DB pool, then process.exit(0).
  4. Dockerise – Write a lightweight Dockerfile (node:alpine base), copy package*.json, run npm ci, and expose the port. Test with docker build and docker run.
  5. Small project – Deploy the Todo API to a local Docker container, hit the endpoints with curl or Postman, and verify logs, error handling, and graceful stop.

By the end of the month you will have a production‑grade Express service that mirrors the architectural concerns you’re used to in Spring Boot, while feeling comfortable with the JavaScript ecosystem.


FAQ

How do I replicate Spring Boot’s auto‑configuration?

Use libraries that provide sensible defaults (e.g., express.json() for body parsing, helmet for security). You can also create a small “bootstrap” module that wires common middleware so each new service starts with the same stack.

Do I need TypeScript to get type safety?

Not strictly. JavaScript works fine, but adding TypeScript (npm install -D typescript @types/express) gives you compile‑time checks similar to Java and is worth the modest setup cost.

What’s the best way to organize files?

A common convention is: src/ for source, src/routes/ for routers, src/controllers/ for business logic, src/models/ for DB schemas, src/middleware/ for reusable middleware, and src/config/ for configuration files. Adjust as the project grows.

How do I handle dependency injection without Spring?

Start with manual wiring: create service classes and pass them to routers via closure. When the codebase grows, adopt a lightweight DI container like awilix—it mimics Spring’s “register‑then‑resolve” pattern without the heavy annotation processing.

Keep going

Originally published at switchbyskill.com.

Top comments (0)