chrstphrknwtn / now-dev-router

Use Zeit Now v2 routes in a custom server.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

-- Deprecated --

This was just a band-aid whilst the now dev command support for routes was poor. This package is deprecated in favour of using now dev directly.

now-dev-router

A bandaid router for using Now v2 routes in a custom server, stolen wholesale from zeit/now-cli/.../dev-router.ts.

Usage

const { createServer } = require('http');
const router = require('now-dev-router');

createServer((req, res) => {
  const route = router(req.url, routes);
  if (route.found) {
    // Do something the route
  } else {
    // Do something else
  }
});

Next.js Custom Server

const { createServer } = require('http');
const next = require('next');
const parse = require('url-parse');
const router = require('now-dev-router');
const { routes } = require('./now.json');

const dev = process.env.NODE_ENV !== 'production';
const PORT = process.env.PORT || 4000;

const app = next({ dev });
const requestHandler = app.getRequestHandler();

app.prepare().then(
  createServer((req, res) => {
    const router = devRouter(req.url, routes);
    const parsedUrl = parse(req.url, true);
    if (route.found) {
      app.render(req, res, route.dest, { ...route.uri_args, ...parsedUrl.query });
    } else {
      requestHandler(req, res, parsedUrl);
    }
  }).listen(PORT, err => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${PORT}`);
  })
);

About

Use Zeit Now v2 routes in a custom server.


Languages

Language:JavaScript 100.0%