Backend from First Principles

Topic 3 of 4

Serialization

The core problem

Interview answer

The frontend is JavaScript, and the backend might be Python, Go or Rust. They can't read each other's objects from memory. So both sides agree on a common text format, JSON, to send data over the network.

Sending a JavaScript object to a Rust server

No common format

JS clientRust serverJS client holds—

Agreed format: JSON

JS clientRust serverJS client holds—Rust server holds—

Press ▶ Play or “Next step”. Arrow keys work too.

Debug view

No common format
Step through the diagram to see requests and responses.
Agreed format: JSON
Step through the diagram to see requests and responses.

What is serialization?

Interview answer

Serialization means turning my in-memory data into something I can send, like a JSON string. Deserialization is turning that string back into an object on the other side. In JavaScript that's JSON.stringify and JSON.parse.

The complete journey
ClientJavaScriptNetworkServerClient holds—Server holds—

Press ▶ Play or “Next step”. Arrow keys work too.

Debug view

Step through the diagram to see requests and responses.

Text vs binary formats

Interview answer

Text formats like JSON, XML and YAML are readable by humans but bigger. Binary formats like Protobuf are raw bytes: smaller and faster, but you can't read them without a tool. REST APIs almost always use JSON.

CategoryExamplesWhen used
TextJSON, XML, YAMLREST APIs, config files, logs
BinaryProtobuf, AvroHigh-performance service-to-service

The same user, { name: "Ali", age: 25 }, in both:

JSON is the default for REST APIs. You'll rarely use XML or binary formats unless a system requires it.

json
{"name":"Ali","age":25}
bash
# Protobuf (schema: name = field 1, age = field 2): 7 bytes instead of 23
0a 03 41 6c 69 10 19

JSON rules

Interview answer

Keys must be in double quotes. Values can be a string, number, true/false, null, an array or an object. No comments and no trailing commas. And a JSON document doesn't have to be an object: [1,2,3] and "hello" are valid too.

JSON playground

✓ Valid JSON. Top-level value: object

JSON.parse(text)   // typeof → "object"
{
  "name": "Ali",
  "age": 25,
  "active": true,
  "skills": [
    "Node",
    "Postgres"
  ],
  "address": {
    "city": "Rawalpindi",
    "country": "Pakistan"
  }
}

JSON (JavaScript Object Notation) isn't limited to JavaScript; every language reads and writes it. It's used in REST requests and responses, log files, and config files like package.json and tsconfig.json.

  • A JSON document can be any JSON value: an object {…}, an array […], a string, a number, true/false, or null. It doesn't have to start with {.
  • All keys must be strings in double quotes: "name", not name or 'name'.
  • Values can only be: string, number, boolean, null, array, or another object.
  • No comments.
  • No trailing commas.

The backend engineer's mental model

Interview answer

Under the hood, my JSON gets wrapped in HTTP, split into TCP packets and routed over IP. But when it reaches the server it's exactly the same JSON string again. As a backend developer, I only work with that JSON.

What happens underneath (and why you can ignore it)
Client appapplicationClient networkHTTP · TCP · IPServer networkIP · TCP · HTTPYour serverapplication

Press ▶ Play or “Next step”. Arrow keys work too.

Debug view

Step through the diagram to see requests and responses.

Code: serialize and deserialize in Node

Interview answer

JSON.stringify turns an object into a JSON string; JSON.parse turns it back. In Express, express.json() parses every request body into req.body, and res.json() stringifies my response and sets Content-Type.

What Express does automatically:

Without Express, this is the work express.json() and res.json() hide:

js
const user = { name: 'Ali', age: 25 }

const jsonString = JSON.stringify(user) // SERIALIZE → '{"name":"Ali","age":25}'  (string)
const jsObject = JSON.parse(jsonString) // DESERIALIZE → { name: 'Ali', age: 25 }  (object)
js
app.use(express.json()) // deserializes every JSON request body (without it, req.body is undefined)

app.post('/users', (req, res) => {
  const user = req.body // already a JS object
  res.status(201).json({ created: user }) // serializes + sets Content-Type: application/json
})
js
const http = require('http')

http.createServer((req, res) => {
  if (req.method === 'POST' && req.url === '/users') {
    let body = ''
    req.on('data', (chunk) => (body += chunk)) // collect raw chunks from the stream
    req.on('end', () => {
      let user
      try {
        user = JSON.parse(body) // manually deserialize
      } catch {
        res.writeHead(400, { 'Content-Type': 'application/json' })
        return res.end(JSON.stringify({ error: 'invalid JSON' })) // bad JSON must not crash the server
      }
      res.writeHead(201, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({ created: user })) // manually serialize
    })
  }
}).listen(3000)

Quick revision

TermOne line
SerializationYour data into JSON before sending
DeserializationJSON back into your data after receiving
JSONText-based, human-readable, the standard for REST APIs
Binary formatsProtobuf, Avro: smaller and faster, not human-readable
JSON.stringify()JS value → JSON string
JSON.parse()JSON string → JS value (throws on invalid input)
express.json()Auto-deserializes every JSON request body
res.json()Auto-serializes the response and sets Content-Type

Quiz

Think of the answer first, then reveal it.

0/10 answers revealed
  1. Q1 · concept

    What are serialization and deserialization?

  2. Q2 · concept

    Why can't a JavaScript client just send its object to a Rust or Python server?

  3. Q3 · concept

    Text vs binary formats: examples and trade-offs?

  4. Q4 · concept

    Is [1, 2, 3] valid JSON? What about "hello" or null?

  5. Q5 · scenario

    What's wrong with { name: 'Ali', age: 25, } as JSON?

  6. Q6 · concept

    What do express.json() and res.json() do under the hood?

  7. Q7 · scenario

    req.body is undefined in your POST handler. Why?

  8. Q8 · scenario

    Your plain Node server crashes when a client sends malformed JSON. Why, and how do you fix it?

  9. Q9 · concept

    As a backend engineer, which network layer do you work with, and why can you ignore the rest?

  10. Q10 · concept

    Walk through the full request/response serialization flow for a form submit to Express.