Blitz is in beta! 🎉 1.0 expected in May or June
Back to Documentation Menu

Custom Server


Jump to a Topic

You can use the custom server feature if you need websocket support or some other direct control over the web server itself.


  1. Add a server.js file in your project root. See below for an example.
  2. Now blitz dev and blitz start will automatically detect and use your custom server.


Here's an example custom server:

// server.js
const {createServer} = require("http")
const {parse} = require("url")
const blitz = require("blitz/custom-server")

const dev = process.env.NODE_ENV !== "production"
const app = blitz({dev})
const handle = app.getRequestHandler()

app.prepare().then(() => {
  createServer((req, res) => {
    // Be sure to pass `true` as the second argument to `url.parse`.
    // This tells it to parse the query portion of the URL.
    const parsedUrl = parse(req.url, true)
    const {pathname, query} = parsedUrl

    if (pathname === "/a") {
      app.render(req, res, "/a", query)
    } else if (pathname === "/b") {
      app.render(req, res, "/b", query)
    } else {
      handle(req, res, parsedUrl)
  }).listen(3000, (err) => {
    if (err) throw err
    console.log("> Ready on http://localhost:3000")

server.js doesn't go through babel or webpack. Make sure the syntax and sources this file requires are compatible with the current node version you are running.

The custom server uses the following import to connect the server with the Blitz application:

The above blitz import is a function that receives an object with the following options:

  • dev: Boolean - Whether or not to launch Blitz in dev mode. Defaults to false
  • dir: String - Location of the Blitz project. Defaults to '.'
  • quiet: Boolean - Hide error messages containing server information. Defaults to false
  • conf: object - The same object you would use in blitz.config.js. Defaults to {}

The returned app can then be used to let Blitz handle requests as required.

Disabling file-system routing

By default, blitz will serve each file in the pages folder under a pathname matching the filename. If your project uses a custom server, this behavior may result in the same content being served from multiple paths, which can present problems with SEO and UX.

To disable this behavior and prevent routing based on files in pages, open blitz.config.js and disable the useFileSystemPublicRoutes config:

module.exports = {
  useFileSystemPublicRoutes: false,

Note that useFileSystemPublicRoutes disables filename routes from SSR; client-side routing may still access those paths. When using this option, you should guard against navigation to routes you do not want programmatically.

You may also wish to configure the client-side router to disallow client-side redirects to filename routes; for that refer to router.beforePopState.

Idea for improving this page? Edit it on GitHub.