:desktop_computer: Simple and powerful server for Node.js

Overview

server.js for Node.js

Subscribe Downloads Status Dependencies status

Powerful server for Node.js that just works so you can focus on your awesome project:

// Include it and extract some methods for convenience
const server = require('server');
const { get, post } = server.router;

// Launch server with options and a couple of routes
server({ port: 8080 }, [
  get('/', ctx => 'Hello world'),
  post('/', ctx => {
    console.log(ctx.data);
    return 'ok';
  })
]);

Simplicity is a great virtue but it requires hard work to achieve it and education to appreciate it. And to make matters worse: complexity sells better.

― Edsger W. Dijkstra

Getting started

There's a whole tutorial on getting started for beginners but the quick version is to first install server as a dependency:

npm install server

Server requires Node.js 7.6.0 or newer. Node.js 8.x.y LTS is recommended.

Then you can create a file called index.js with this code:

// Include the server in your file
const server = require('server');
const { get, post } = server.router;

// Handle requests to the url "/" ( http://localhost:3000/ )
server([
  get('/', ctx => 'Hello world!')
]);

Execute this in the terminal to get the server started:

node .

And finally, open your browser on localhost:3000 and you should see 'Hello world!' on your browser.

Documentation

The library is documented here:

Full Documentation

Subscribe here to receive tutorials when released. Tutorials are good for learning while the documentation is good for reference/quick use once you know the basics.

You can also download the repository and try the examples by browsing to them and node . inside each of them in /examples.

Use cases

The package server is great for many situations. Let's see some of them:

Small to medium projects

Everything works out of the box, you get great support for most features and you can easily tap into Express' middleware ecosystem. What's not to love?

Some of the included features: body and file parsers, cookies, sessions, websockets, Redis, gzip, favicon, csrf, SSL, etc. They just work so you will save a headache or two and can focus on your actual project. Get a simple form going:

const server = require('server');
const { get, post } = server.router;
const { render, redirect } = server.reply;

server(
  get('/', () => render('index.pug')),
  post('/', ctx => {
    console.log(ctx.data);
    return redirect('/');
  })
);

API design

From the flexibility and expressivity of the bundle, designing APIs is a breeze:

// books/router.js
const { get, post, put, del } = require('server/router');
const ctrl = require('./controller');

module.exports = [
  get('/book', ctrl.list),
  get('/book/:id', ctrl.item),
  post('/book', ctrl.create),
  put('/book/:id', ctrl.update),
  del('/book/:id', ctrl.delete)
];

Real time

Websockets were never this easy to use! With socket.io on the front-end, you can simply do this in the back-end to handle those events:

// chat/router.js
const { socket } = require('server/router');
const ctrl = require('./controller');

module.exports = [
  socket('connect', ctrl.join),
  socket('message', ctrl.message),
  socket('disconnect', ctrl.leave)
];

Author & support

This package was created by Francisco Presencia but hopefully developed and maintained by many others. See the the list of contributors here.

I love using my work and I'm available for contractor work. Freelancing helps maintain server and my other open source projects up to date! I am also on Codementor so if you want to learn more Javascript/Node.js/etc contact me there.

You can also sponsor the project, get your logo in here and some other perks with tons of

Comments
  • How to authenticate

    How to authenticate

    I am curious on how to authenticate using server. I don't see how to configure my session store to be mongoDB using connect-mongo. A tutorial on how to this will be really helpful.

    bug fixed? 
    opened by franckstifler 18
  • Wildcard Method Requests

    Wildcard Method Requests

    Description

    The current method implementations don't support catch-all endpoints.

    Requested Syntax

    const server = require('server');
    const { status } = server.reply;
    const { get } = server.router;
    
    server(
      // This should get invoked for every request
      // An alternative syntax would be to support Regular Expressions.
      get('*', (ctx) => {
        return status(200);
      })
    );
    

    Current Workaround

    const server = require('server');
    const { status } = server.reply;
    
    server(
      (ctx) => {
        if (ctx.method !== 'GET') return;
    
        // Do super cool api stuff
        return status(200);
      })
    );
    

    Relevant Code

    The following code doesn't support wildcards / catch-all endpoints.

    https://github.com/franciscop/server/blob/dd1ad51bcd1cd80f64ff119e75edb51d3b6acbd9/router/generic.js#L21-L23

    opened by cecilia-sanare 16
  • Nunjucks broken using engine = {nunjucks: } on Server.js Version server@1.1.0-alpha.3

    Nunjucks broken using engine = {nunjucks: } on Server.js Version [email protected]

    Description

    after running node index.js on the new [email protected] version and attempting to use the new engine = {nunjucks: }, server.js fails with "Error: Module "nunjucks" does not provide a view engine."

    The code used for nunjucks templating is essentially what your provide, I only added a "port" to the options:

    // Import the library
    const server = require('server');
    const express = require('express');
    const nano = require('nano')('http://localhost:5984');
    
    const settings = require('settings');
    
    const app = express;
    const { get, post } = server.router;
    const { render, json, redirect, status } = server.reply;
    
    const nunjucks = require('nunjucks');
    var env = nunjucks.configure('views'); 
    
    const engine = {
        port: settings.PORT,
      nunjucks: (file, options) => require('nunjucks').render(file, options)
    };
    
    
    server(engine, ctx => render('index.nunjucks', {  }));
    

    I hope to eventually contribute documentation as I attempted to before and maybe even code if I can become better at Node :+1:

    Expected outcome

    after running node index.js, I should be able to see the standard HTML template using standard nunjucks templating.

    Actual outcome

    [Tue Mar 06 2018 17:20:10 GMT-0600 (CST)] ERROR Error: Module "nunjucks" does not provide a view engine.
        at new View (/home/acer/nodespace/node_modules/express/lib/view.js:84:13)
        at Function.render (/home/acer/nodespace/node_modules/express/lib/application.js:570:12)
        at ServerResponse.render (/home/acer/nodespace/node_modules/express/lib/response.js:1008:7)
        at Promise (/home/acer/nodespace/node_modules/server/reply/reply.js:139:13)
        at new Promise (<anonymous>)
        at stack.push.ctx (/home/acer/nodespace/node_modules/server/reply/reply.js:136:26)
        at Reply.exec (/home/acer/nodespace/node_modules/server/reply/reply.js:175:11)
        at processReturn (/home/acer/nodespace/node_modules/server/src/join/index.js:11:22)
        at Object.middle (/home/acer/nodespace/node_modules/server/src/join/index.js:43:17)
        at <anonymous>
    
    

    Live Demo

    No live demo :(

    System Information

    Ubuntu 16.04

    Node Version: v8.9.1

    Server.js Version: [email protected]

    fixed? 
    opened by coderam 13
  • Ability to provide a custom logger

    Ability to provide a custom logger

    This PR adds a new instance option to the log plugin.

    Please read updated README.md included within this PR for details.

    • [x] Implementation
    • [x] Updated tests
    • [x] Updated documentation
    opened by amercier 11
  • Support changing the template engine, includes an example

    Support changing the template engine, includes an example

    I've put the engine change as a separate commit to the inclusion of the template in case you want to cherry-pick only that change.

    The example documentation on the site depends on my PR #4 being included.

    I don't know if this is the best way to do it but this is one way I got it working which I wanted to try before just creating an issue.

    I've done some testing I can think of to make it work but this could probably use some actual written tests.

    opened by Jackbennett 10
  • How to create, set a name and send a file dynamically create

    How to create, set a name and send a file dynamically create

    Context

    This not a real issue. I found the answer on the way of writing it, but I decided to still create this issue in case others may have the same question and to add some remarks:

    • I think the documentation should include clearly that this is a wrapper around express, because reading the code is very hard without that knowledge (I searched for quite a while a function that was outside your project).
    • Maybe the following would be a good addition to your API? But I'm not really sure, that seems qui generic too me but maybe few people need this.

    The question

    I'm creating a PDF file on the flight (on each request) but I can't find a way to send it. The server.reply.download function only allows to give the name of the file you want to download. In my case, I have no file name and I would like to avoid creating dealing with file system.

    Is there any way to do this? Also that would be nice to allow giving a name to the file when downloaded by the client.

    docs 
    opened by cglacet 9
  • Handling Files

    Handling Files

    Description

    Documentation has very little on how to handle files other than logging out its name.

    Expected outcome

    would be nice for the documentation to show about saving files or doing something with the file content.

    System Information

    Windows 10 :(

    Node Version: v8.9.4

    Server.js Version: 1.0.18

    docs 
    opened by vorticalbox 8
  • Server is not setting session cookies

    Server is not setting session cookies

    Running latest from npm I have a simple GET route and the server response does not contain any cookies. The next weird part is. Since the browser gets no cookie its not sending any cookie, however I have a simple visit counter setup in the session and it appears to increment with each visit regardless of using multiple browsers. The server seems to be keeping some kind of shared session which it uses for any client that does not provide a session cookie.

    The next odd thing is I have Redis setup for sessions and have confirmed the server is connected to Redis however if I restart the server the visit counter is lost.

    I am at a loss as how to debug this one....

    tests bug 
    opened by paulrobello 7
  • Server and Nunkunks

    Server and Nunkunks

    Hi Guys, someone can tell me how use server.js with nunjucks as template render? I can use server.js with nunjucks using this:

    const server = require('server')
    const { get } = server.router
    
    const njk = require('nunjucks')
    njk.configure('views')
    
    server(
      get('/', ctx => njk.render('template.njk')),
    )
    

    or:

    const server = require('server')
    const njk = require('nunjucks')
    
    const { get, post } = server.router
    const { render } = server.reply
    
    server(
      get('/', ctx => render('template.njk')),
    ).then((v) => njk.configure('views', {express: v.app}))
    

    What is the best flow?

    Thanks for your time and for this great lib.

    opened by dannluciano 7
  • Doesn't work on Windows!

    Doesn't work on Windows!

    For some reason the files served with the static middleware don't load on Windows.

    1. Find the bug (check absolute paths and C:// issues).
    2. Fix the bug.
    3. Establish a testing methodology that involves windows as well.
    bug 
    opened by franciscop 7
  • Any schedule for migrating to socket.io 4.x?

    Any schedule for migrating to socket.io 4.x?

    The socket.io using now is v 2.x, which means client using v3.x / 4.x will not be able to connect. I would like to know is there any plan for updating it?

    opened by lantica 6
  • [PSA] update to server@1.0.38 for `rediss://` usage

    [PSA] update to [email protected] for `rediss://` usage

    That's it, update [email protected] for an updated version of connect-redis and ioredis that support the rediss:// protocol (as well as the redis:// protocol). Please let me know if there's any bug with the upgrade.

    Example for it to work, just add the key in .env:

    #.env
    REDIS_URL=rediss://[omitted]
    
    announcement 
    opened by franciscop 0
  • Add CORS package to the core

    Add CORS package to the core

    Is your feature request related to a problem? Please describe. One of the basic features of APIs is to be able to work nicely with CORS. This is not possible with Server.js, and instead you need to either install a third party package or do it manually.

    Describe the solution you'd like Have the cors package be a part of the core. It should be disabled by default, but easily be able to do:

    server({ cors: false });   // Default (to keep it retro-compatible)
    server({ cors: "*" });
    server({ cors: "https://serverjs.io" });
    server({ cors: ["https://serverjs.io", "http://localhost:3000"] });
    server({
      cors: { origin: "https://serverjs.io",  methods: ["GET", "PUT", "POST"] }
    });
    

    Describe alternatives you've considered Using the cors package; it'd be nice to have it in the core so we don't need to install it each time.

    Additional context Since server.js is supposed to work nicely both as an API server and as a renderer (traditional) server, this makes making an API easier.

    new-feature 
    opened by franciscop 0
Releases(1.0.17)
  • 1.0.17(Jan 13, 2018)

  • 1.0.16(Jan 13, 2018)

    Added hook for options within a plugin options so you can have a subschema in a plugin option schema. Example:

    // For the plugin @server/auth
    module.exports = {
      name: 'auth',
      callback: { type: String },
      options: {
        facebook: {
    
          // Note: these 2 should be not needed in the future
          default: {},
          extend: true,
    
          // This is the new thing that you can do:
          options: {
            id: { type: String, env: 'FACEBOOK_ID' },
            secret: { type: String, env: 'FACEBOOK_SECRET' }
          }
    
        }
      }
    };
    

    Then when using the plugin it will be like this:

    server({
      auth: {
        facebook: {
          id: 'whatever',
          secret: 'whatever'
        }
      }
    });
    

    But of course for this specific example you'd use the .env:

    # .env
    FACEBOOK_ID=whatever
    FACEBOOK_SECRET=whatever
    
    Source code(tar.gz)
    Source code(zip)
  • 1.0.15(Jan 1, 2018)

  • 1.0.14(Jan 1, 2018)

  • 1.0.13(Jan 1, 2018)

  • 1.0.12(Jan 1, 2018)

    Remove the default body that was set by express when only an status code was sent by making it explicit with status(NUMBER).send(). Also fixes #46

    Source code(tar.gz)
    Source code(zip)
  • 1.0.10(Jan 1, 2018)

  • 1.0.9(Jan 1, 2018)

  • 1.0.8(Jan 1, 2018)

  • 1.0.7(Jan 1, 2018)

    Yarn and npm have different path resolution. Manually attached path-to-regexp-wrap, which fixes #43

    This was giving inconsistent results when using yarn (vs the expected one with npm):

    server(
      get('*', (ctx) => {
        return status(200);
      })
    );
    
    Source code(tar.gz)
    Source code(zip)
Owner
Francisco Presencia
Twitter: @fpresencia
Francisco Presencia
Modern framework for fast, powerful React apps

FUSION.JS Modern framework for fast, powerful React apps What is it? fu·sion — noun The process or result of joining two or more things together to fo

Fusion.js 1.5k Dec 30, 2022
Noderlang - Erlang node in Node.js

Noderlang allows Node.js programs to easily operate in BEAM environments

devsnek 2 Mar 31, 2022
Actionhero is a realtime multi-transport nodejs API Server with integrated cluster capabilities and delayed tasks

Actionhero The reusable, scalable, and quick node.js API server for stateless and stateful applications NPM | Web Site | Latest Docs | GitHub | Slack

Actionhero 2.3k Dec 29, 2022
A simple boilerplate generator for your node express backend project! 🚀

A simple boilerplate generator for your node express backend project! ??

Gunvant Sarpate 35 Sep 26, 2022
wolkenkit is an open-source CQRS and event-sourcing framework based on Node.js, and it supports JavaScript and TypeScript.

wolkenkit wolkenkit is a CQRS and event-sourcing framework based on Node.js. It empowers you to build and run scalable distributed web and cloud servi

the native web 1.1k Dec 26, 2022
Clock and task scheduler for node.js applications, providing extensive control of time and callback scheduling in prod and test code

#zeit A node.js clock and scheduler, intended to take place of the global V8 object for manipulation of time and task scheduling which would be handle

David Denton 12 Dec 21, 2021
Elegant and all-inclusive Node.Js web framework based on TypeScript. :rocket:.

https://foalts.org What is Foal? Foal (or FoalTS) is a Node.JS framework for creating web applications. It provides a set of ready-to-use components s

FoalTS 1.7k Jan 4, 2023
Micro type-safe wrapper for Node.js AMQP library and RabbitMQ management.

Micro type-safe wrapper for AMQP library and RabbitMQ management Description Section in progress. Getting Started Qupi can be installed by Yarn or NPM

Grzegorz Lenczuk 2 Oct 5, 2021
DDD/Clean Architecture inspired boilerplate for Node web APIs

Node API boilerplate An opinionated boilerplate for Node web APIs focused on separation of concerns and scalability. Features Multilayer folder struct

Talysson de Oliveira Cassiano 3k Dec 30, 2022
🚀 A RESTful API generator for Node.js

A RESTful API generator rest-hapi is a hapi plugin that generates RESTful API endpoints based on mongoose schemas. It provides a powerful combination

Justin Headley 1.2k Dec 31, 2022
nact ⇒ node.js + actors ⇒ your services have never been so µ

nact ⇒ node.js + actors your services have never been so µ Any and all feedback, comments and suggestions are welcome. Please open an issue if you fin

Natalie Cuthbert 1k Dec 28, 2022
A Programming Environment for TypeScript & Node.js built on top of VS Code

Programming Environment for TypeScript & Node.js A battery-included TypeScript framework built on top of Visual Studio Code Website Kretes is a progra

Kretes 677 Dec 11, 2022
Full stack CQRS, DDD, Event Sourcing framework for Node.js

reSolve is a full stack functional JavaScript framework. CQRS - independent Command and Query sides. DDD Aggregate support. Event sourcing - using eve

ReImagined 709 Dec 27, 2022
In-memory filesystem with Node's API

In-memory filesystem with Node's API

Vadim Dalecky 1.4k Jan 4, 2023
💻 Simple and flexible CLI Tool for your daily JIRA activity (supported on all OSes)

jirax ⭐ If you are using this tool or you like it, Star on GitHub — it helps! A CLI tool for JIRA for day to day usage with JIRA.Speed up your JIRA ac

জুনিপ 56 Oct 4, 2022
A nodejs module for local and remote Inter Process Communication with full support for Linux, Mac and Windows

A nodejs module for local and remote Inter Process Communication with full support for Linux, Mac and Windows

Rifa Achrinza 15 Sep 28, 2022
:zap: RAN! React . GraphQL . Next.js Toolkit :zap: - SEO-Ready, Production-Ready, SSR, Hot-Reload, CSS-in-JS, Caching, CLI commands and more...

RAN : React . GraphQL . Next.js Toolkit New version is coming... Follow up here: https://github.com/Sly777/ran/issues/677 Features Hot-Reload Ready fo

Ilker Guller 2.2k Jan 3, 2023
Fast and type-safe full stack framework, for TypeScript

Fast and type-safe full stack framework, for TypeScript Why frourio ? Even if you write both the frontend and backend in TypeScript, you can't statica

frourio 1.1k Dec 26, 2022