Babel Node Express: Modern Syntax, Old HTTP
Babel translates syntax, not an execution model – once you keep the two apart, you know why babel-node belongs in the development loop and not in production.
Babel Node Express: Modern Syntax, Old HTTP
$ node src/server.js
/app/src/server.js:1
(function (exports, require, module, __filename, __dirname) { import express from 'express';
^^^^^^
SyntaxError: Unexpected token import
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
This is how Node 6 responds to a file that starts with an import. The message is short, and the confusion behind it is reliable: the same line appears in what feels like every other tutorial this year, it runs in the frontend build without complaint – only the runtime that is supposed to actually run the server in the end doesn’t know the keyword. ES2015 was approved a year and a half ago, V8 has built in a large part of it, and still startup fails on the first line of the first file.
The occasion for this post is a small repository I put together in early December: babel-node-expressjs, a deliberately simple Express app, written entirely in ES2015+ and made runnable with Babel. A second one came out of the same day, babel-node-rx-ping-monitor, which pushes RxJS through the same toolchain – but that has a topic of its own and deserves its own text. This post is about the dividing line that became visible during setup and that gets blurred surprisingly often in discussions: Babel changes the language, not the execution model. The syntax became modern in 2016. The HTTP underneath stayed the same.
What Node 6 and 7 can already do on their own#
Before Babel comes into play, it’s worth taking a sober look at what the platform handles without any tool. Node 6 has been the active LTS line since October, Node 7 the current development line, and through V8 both already ship a substantial part of ES2015 natively:
- Classes including
extendsandsuper constandletwith real block scoping- Template literals, arrow functions, default parameters
- Destructuring for objects and arrays
- Promises and generators
If you want to check in detail what your own Node version covers, node.green has a matrix per version and feature. The list is longer than many assume – and that is exactly why the blanket statement “you need Babel for ES2015” is now off the mark. For most of the language, you simply don’t need it anymore.
Two prominent gaps remain. async/await exists in Node 7 only experimentally behind the --harmony-async-await flag – for code that is supposed to carry a server, that’s not a foundation but a preview. And import/export is missing entirely: the module syntax is part of the specification, but what a loader in Node should look like and how ES modules work together with the established CommonJS ecosystem is unresolved. A native ES module system is nowhere in sight. If you write import in the backend today, you’re writing syntax for a runtime that doesn’t exist in that form yet – and that’s why you need a translator.
The app: Express 4 in today’s style#
The server in the repository deliberately does little – one JSON route, one route for URL-encoded form data, both demonstrated in the README:
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
const port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.json({ message: 'hello' });
});
app.post('/', (req, res) => {
const { msg } = req.body;
res.json({ received: msg });
});
app.listen(port, () => {
console.log(`server listening on port ${port}`);
});
What’s interesting isn’t what this code does but how it looks: import instead of require, arrow functions instead of function, const instead of var, destructuring on the request body, a template literal in the log. This is the style that finally won out in the frontend this year, and there’s no good reason to maintain an older language level in the backend than in the rest of the project. Uniform syntax reduces friction when the same people touch React components in the morning and Express routes in the afternoon.
On the side, you also see a bit of Express 4 history here: body parsing is no longer a built-in function but comes as a separate body-parser package and is plugged in as middleware per format. If you come from Express 3, this is exactly where you stumble first – and that has nothing to do with Babel and all the more to do with HTTP.
On the wire, this changes exactly nothing. A POST to http://localhost:3000 with a URL-encoded form field – the README has the matching one-liner – sends the same bytes as against any Express app of the last three years, and the answer is the same HTTP response with the same headers. Middleware chain, body parsing, status codes, content negotiation – the complete HTTP behavior is untouched by the syntax question. That sounds trivial. But it’s the core of the topic, because this is exactly where the misunderstandings arise.
What babel-node does in development mode#
For the file to start at all, you need two things: a translation rule and a tool that applies it. The rule lives in .babelrc:
{
"presets": ["es2015"]
}
The es2015 preset is the established way with Babel 6. Brand new alongside it is babel-preset-env, which, via a targets field, only transpiles what the target Node version actually can’t do – more on that in a moment. The tool for development is called babel-node and ships with babel-cli. It starts a normal Node process, hooks into the require mechanism and translates every loaded file in memory, right before V8 sees it. No dist/ folder, no intermediate step; together with nodemon, that makes for a pleasantly short loop:
{
"scripts": {
"dev": "nodemon --exec babel-node src/server.js",
"build": "babel src --out-dir dist --source-maps",
"start": "node dist/server.js"
}
}
Save the file, nodemon restarts, babel-node translates, the server runs. For development, that’s exactly right, because the feedback is what counts and the process restarts constantly anyway. The only important thing is to be clear about what’s happening: the translation has been pulled into program startup. Every start pays for it again.
The same mechanism, by the way, also carries the tests: babel-register, hooked into mocha, translates the test files on load following the same principle. That, too, is meant for the development loop and is perfectly fine there – a test run is a short-lived process where a few hundred milliseconds of warm-up don’t matter. So the line doesn’t run between “with Babel” and “without Babel,” but between short-lived tool processes and the one process that has to run for a long time and be back quickly after a crash.
flowchart LR
subgraph DEV[Development]
S1[src/server.js<br/>ES2015+] --> BN[babel-node<br/>translates in memory] --> P1[Node process]
end
subgraph PROD[Production]
S2[src/server.js<br/>ES2015+] --> BC[npm run build<br/>babel-cli] --> D[dist/server.js<br/>ES5 + CommonJS] --> P2[node dist/server.js]
endWhat the convenient path costs in production#
It’s tempting to simply use babel-node in production too – one script fewer, one folder fewer, the same command line everywhere. The Babel documentation itself explicitly advises against it, and the reasons are solid:
- Process startup becomes noticeably slower because every file first has to go through the transpiler on boot – with every deployment, every restart after a crash, every process in the cluster all over again.
- Memory usage rises because Babel, including parser, presets and cache, keeps running in the server process even though it contributes nothing after startup.
- Stack traces point to translated code that nobody ever wrote; without properly wired source maps, the line number in the error report points nowhere.
- The debugger works against the generated code, breakpoints land next to the intended line, and the behavior depends on the Babel version installed on the target machine.
I ran into this point concretely in a project this year: a colleague had deployed a small internal service with babel-node, and for weeks nobody noticed. It only came to light when the process restarted under load and the supervisor brought it up several times in a row – each restart several seconds of transpiling, during which the port was open but the service wasn’t responding. The bug wasn’t in any line of application code. It was in the decision to take a development tool into production.
Build first, then start#
The grown-up variant separates translation from startup. npm run build calls babel-cli, translates src/ once into dist/ and puts source maps next to it. What arrives there is unspectacular ES5 with CommonJS – the import at the top of the file becomes exactly what Node has understood for years:
'use strict';
var _express = require('express');
var _express2 = _interopRequireDefault(_express);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
You don’t have to find this generated code pretty, but you should have read it once. It takes all the magic out of the module syntax: after translation, import is a synchronous require at program startup, with a small wrapper for the default export. No new loading logic, no different resolution behavior, no difference at runtime.
The artifact in dist/ has two pleasant properties. First, the target machine no longer needs Babel – node dist/server.js is enough, and the devDependencies stay at home. Second, the startup path is once again the boring one Node has followed for years: start the process, load modules, open the port. The translation happens once per build instead of once per start, and that’s exactly where it belongs. Otherwise, you only notice that there’s a difference between “it runs on my machine with babel-node” and “it runs as a built artifact” at the worst possible moment.
In practice, this also determines where the build happens: in the pipeline, not on the target machine. You build and test once, ship the result, and an installation without devDependencies leaves Babel and its presets off the server entirely. The order in the repo’s README – build, test, only then run – is therefore not a formality but the short version of this operating model.
Language on top, execution model below#
Now to the actual dividing line. Babel works exclusively at the level of the language: it reads syntax that V8 doesn’t understand yet and rewrites it into syntax that V8 does understand. Everything below remains untouched – the event loop, the module system at runtime, streams, sockets, all of HTTP.
flowchart TB B[Babel] -->|changes only this layer| L1 L1[Language: import, classes,<br/>arrow functions, destructuring] --> L2[Runtime: event loop,<br/>CommonJS require, streams] L2 --> L3[HTTP: connections, headers,<br/>request and response]
This separation sounds obvious, but it regularly gets blurred as soon as the new syntax looks like more than it is. Three examples from conversations over the last few months. An import at the top of the file looks declarative and static – after translation, it’s an ordinary require that runs synchronously at startup, in the order of the lines. An arrow function in the route looks lightweight – it runs on the same single thread as everything else, and an expensive JSON serialization inside it blocks the event loop exactly as it did in 2013. And the async previews in Node 7 look like concurrency – in fact they’re just a different way of writing promise chains and change nothing about timeouts, error paths or behavior under load. If you run an Express server with modern syntax, you’re running the same server. The questions that matter in production – how long may a request take, what happens with an aborted body, who shuts down the process cleanly – aren’t answered by any preset.
Conversely, the separation also helps you save. Because Node 6 runs most of ES2015 natively, Babel no longer has to translate the whole language. This is exactly where the brand-new babel-preset-env comes in: you tell it the target environment, and it selects only the transformations that are really missing there.
{
"presets": [
["env", { "targets": { "node": 6 } }]
]
}
For Node 6, what remains is essentially the module syntax. The generated code stays closer to the original, classes stay real V8 classes instead of ES5 prototype imitations, and the build gets faster. The better the platform gets, the thinner the translation layer can be – until one day it might disappear entirely. When it comes to modules, though, I wouldn’t bet on it yet.
What I take away from this#
The two small repos were put together in an afternoon, but the dividing line they show reaches further than the code. Babel is a translator for syntax, not a new execution model – and both directions of this statement are useful. In one direction: the modern style costs nothing in production if you pay for it in the build instead of at process startup; babel-node belongs in the development loop, node dist/ in production. In the other direction: the modern style also doesn’t solve anything that needs solving at the HTTP level. Timeouts, error handling, body limits and restart behavior look exactly the same in ES2015 as in ES5, just prettier.
When async/await arrives without a flag next year, the same question will come up again, with the same answers. The syntax will get a bit more modern again. The HTTP underneath stays the old one – and that’s not bad news, because it means twenty years of knowledge about servers doesn’t have to be renewed with every preset.
Further reading#
- Repository: https://github.com/MikeBild/babel-node-expressjs
- Express documentation: https://expressjs.com/
- babel-preset-env: https://github.com/babel/babel-preset-env
- babel-node in the Babel documentation: https://babeljs.io/docs/babel-node
Revised and translated from German with the help of AI.