Skip to content

Custom server logic / routing #25

Closed

Description

@rauchg
next -s server.js

or in package.json:

{
  "next": {
    "serverHandler": "./server.js"
  }
}

Let's say you want to override the default mapping between filesystem and route, you could set up something like this:

const { renderComponent } = require('next/server')
module.exports = ({ path, req, res }) => {
  if ('/a' === path) {
    return renderComponent(req, './b')
  }
}

The function would receive a context object with the following properties (as far as I have thought about it):

  • path the intended path of the request. This is so that if we request /a.json or /a, the path is still /a, which simplifies the logic for the programmer
  • req the original request from node
  • res the original response from node

The return value can be a Promise. If undefined is returned, it performs the default behavior.
This file provides an opportunity to short-circuit (like send a 301), add global security / authentication requirements, etc.

[1] We might or might not want to transpile this file. Since it's "server-only", I think it's ok to assume it just supports whatever the version of Node.js you're running.

Activity

  1. nodegin commented on Oct 25, 2016

    @nodegin
    Contributor

    Can't get this this to working, I have tried to create a server.js

    const { renderComponent } = require('next/server')
    module.exports = ({ path, req, res }) => {
      console.log(path)
      if ('/a' === path) {
        return renderComponent(req, './pages/index')
      }
    }
    

    but still showing 404 with no logs printed on console

  2. dotcypress commented on Oct 26, 2016

    @dotcypress

    @nodegin this feature isn't implemented yet. 😢

    @rauchg do you wanna PR for that?

  3. rauchg commented on Oct 26, 2016

    @rauchg
    MemberAuthor

    This should be fairly easy to implement. Wanted to hear comments about whether the proposed API makes sense to you all.

  4. malixsys commented on Oct 26, 2016

    @malixsys
    Contributor

    Might be easier to have a convention on say /api/* matching .js files in a server directory...
    Maybe also supporting some koa/express type middleware insertion/signature (req, res, next) => ?

  5. jmfirth commented on Oct 26, 2016

    @jmfirth

    Without realizing this issue existed I have done some work toward this already. It allows for custom endpoints placed in an /api folder. Perhaps the modifications might interest someone here: jmfirth@c42b562

    Outline of changes:

    • Add new webpack entry points
    • Modify applicable webpack loader include/exclude conditions
    • Add custom render method
    • Add a route entry

    An example endpoint /api/hello.js:

    export default function ({ req, res, params }, { dir, dev }) {
      return { message: 'Hello world!' }
    }

    And response from /api/hello:

    {"success":true,"body":{"message":"Hello world!"}}
  6. neb-b commented on Oct 26, 2016

    @neb-b

    @jmfirth That looks great and is exactly what I am looking for. I can also see it being very useful as I have a really small app with only a few api calls. It would be awesome not to have to create a separate server project for my app.

    What are the dir and dev variables?

  7. jmfirth commented on Oct 26, 2016

    @jmfirth

    dev is presumably a development mode flag

    dir appears to be an injectable root module path that defaults to process.cwd()

    A more general answer is that it follows the same general convention that the render method follows. Both seem like they could be potentially useful for someone developing endpoints.

  8. nodegin commented on Oct 26, 2016

    @nodegin
    Contributor

    this should be merged into master

  9. davibe commented on Oct 26, 2016

    @davibe
    Contributor

    After reading the home page of the project and this issue some things are not clear to me. Please, consider that i only have a very superficial understanding of the project but maybe my doubts can help you clarify some things about the project itself even in the home page.

    1. code may need to be able to do something when both entering on a route and leaving a route

    2. If you perform some task (i.e. data fetching) it needs to be clear wether re-entering the same route causes a redraw or not

    3. sub-routes like product/:id/comments/:cid/author?expanded=true means that a child component may need to access "parent" parts of the url, the data fetched by parent components, url parameters.

    4. with the lack of client-side state and routing, the only thing left to be universal is just the views code (?). I may be missing something but that sounds like too little to call it universal. What's the advantage beside components and their reusability?

  10. jaredpalmer commented on Oct 26, 2016

    @jaredpalmer
    Contributor

    Would you allow for renderJSON too?

  11. rauchg commented on Oct 26, 2016

    @rauchg
    MemberAuthor

    I think it'd be really smart to expose a micro type contract: you can resolve the promise to an object and it gets rendered as JSON automatically :)

  12. rauchg commented on Oct 26, 2016

    @rauchg
    MemberAuthor

    Also, if you want to parse incoming JSON, you can just use micro tools!

    import { json } from micro
    export default async function ({ req, res }) {
      if (path === '/woot') {
        const body = await json(req)
      }
    }

    I like this a lot as it preserves minimalism and great performance while allowing for unlimited power!

  13. rauchg commented on Oct 26, 2016

    @rauchg
    MemberAuthor

    @davibe

    1. You can do this with lifecycle hooks. didMount / unmount
    2. This is also up to react and componentWillReceiveProps, shouldUpdate, etc
    3. You parse the url, you decide what component gets rendered by turning the URL into query data. The URL can be "polymorphic", ie: it can point to any component.
    4. We support both client side state and routing. Redux example: https://github.com/zeit/next.js/wiki/Redux-example. I don't see how you can be more universal than this.
  14. dotcypress commented on Oct 26, 2016

    @dotcypress

    Will be nice to have method for serving static files.

    import { sendFile } from 'next/server'
    export default async function ({ path, req, res }) {
      if (path === '/foo/bar.png') {
        await sendFile(res, './build/bar.png')
      }
    }
  15. 12 remaining items

  16. mbilokonsky commented on Oct 31, 2016

    @mbilokonsky

    Specifically, rather than adding server support to next, I feel like there's one tool missing from the zeit stack - an orchestration layer that essentially just exposes middleware routing. It becomes your server, and each endpoint of your server gets delegated to a standalone micro project.

    So let's call this project orchestrator or something. You'd npm install orchestrator, and it would give you some CLI commands.

    It could step you through some basic questions, do you want a view layer, do you want a service layer, do you want secrets and environment variables, etc. It stores all of this to an orchestra config file.

    If you opted to include a view layer, it could create a subproject that uses next to stub that out. (or, down the line, next could be one of several offerings - could do angular or elm or clojurescript stubs here, too, this could be pluggable).

    If you opted to include an API layer, it could create an 'api' folder with one default micro instance that just sings at /api/ping and returns pong, with some stubbed out tests for it.

    You get a routes file that allows you to parse request URLs as @rauchg mentions above and maps them to specific client pages or service endpoints.

    The whole thing has git support to treat it as a single project, but each service and each next project gets its own deployment logic to get pushed out to autoscaling now instances. So you have the feeling of working on a single application, but under the hood it's all pieces and parts that know how to work together.

    You could have npm run dev to run all of your services locally on different ports (and your middleware tier can just be aware of this), or you could have npm run deploy:dev which deploys your services out to now instances with your dev envars set, or npm run deploy:prod which deploys them with your prod envars sets and auto-aliases the middleware host to your alias.

    I've got a prototype that has started down this road, using now-fleet to handle orchestration and deployment, but there are some things I am still trying to iron out. But I vastly prefer this degree of abstraction, and this orchestrator can be the one-stop-shop turnkey product for stubbing out and deploying huge sites.

    And that's why I think it's a mistake to add custom server support to next, just like it would be for micro. Because ultimately your view engine is just a specialized microservice that returns HTML instead of JSON.

    /phew rant over but I'd love to hear thoughts about this.

  17. rauchg commented on Oct 31, 2016

    @rauchg
    MemberAuthor

    @mbilokonsky I agree that a lot of this can be handled at the proxy level. But we also have to be realistic in that people will need at least some access to the underlying server. This API tries to expose the most minimal surface for doing that, without introducing or advocating bad practices (like tucking your entire server API into one process).

    I'm thinking about writing a document about "best practices" in terms of separation of APIs in the backend for Next to avoid that situation

  18. eirikurn commented on Nov 5, 2016

    @eirikurn

    This would be perfect for sites powered by a CMS api. The handler could query the CMS using the route data and render different page (templates) accordingly.

  19. evantahler commented on Nov 6, 2016

    @evantahler
    Contributor

    For custom routes, why abandon the core the file system is the API rule? I think that is one of the cooler parts of this framework! The biggest problem I'm having is regarding RESTful routing, IE: I've got ./pages/user/view.js which I would like to render for /user/:id. I've got no problem reading the URL... it's just telling Next which partial to render.

    To that end, I suggest using express/rails style route conventions in the file names. So in my example, I would literally name my file ./pages/user/:view.js, and it would work. The name after the : is actually meaningless, here, but it would be cool to inject that into the default exported component as a prop too..., or as part of the url prop that is already being passed in.

  20. evantahler commented on Nov 7, 2016

    @evantahler
    Contributor

    Solving my own problem (#25 (comment)) with #223

  21. eirikurn commented on Nov 7, 2016

    @eirikurn

    I like making the "file system as an api" more powerful, but I also consider that the "default resolver", allowing more powerful url handling when needed.

    Of course this project should not be everything for everyone. But this extension point would open up a lot of cool possibilities. A CMS backed React site being just one of which.

    Speaking of which, it would be nice if renderComponent supported additional context for getInitialProps. This could be used to parameterise the page based on the url and external data (saving a potentially redundant fetch).

  22. tpreusse commented on Nov 14, 2016

    @tpreusse
    Contributor

    I would stick to just routing and think that rails does it well:
    config/routes.rb -> routes.js

    routes.js is guaranteed to only run on the node side and is allowed to access fs. But it is sync as it's not expected to change without a deploy – does not depend on something remote.

    This would look something like this:

    const {route} = require('next/server')
    module.exports = [
      route('/about', {to: 'about'}),
      route('/user/:username', {to: 'user'})
    ];

    to can only point to files in pages (which are webpack entry points / chunks).

    /user/tpreusse would be routed to pages/user which gets params: {username: 'tpreusse'} in getInitialProps. Additionally getInitialProps would expose path_for and url_for which could be used like this: path_for('user', {params: 'tpreusse'}).

    I think in the solution described in the issue description you would still need a way of passing information to the page / component rendered (as @eirikurn also mentioned) and the imperative nature would make it hard to predict routes. My assumption is that with unpredictable routes the code splitting could become hard or sub optimal.

    How would renderComponent work? Wouldn't it be more of a renderPage?

  23. auser commented on Nov 21, 2016

    @auser

    Bump: Curious if there is any movement on this PR?

  24. rauchg commented on Nov 21, 2016

    @rauchg
    MemberAuthor

    Yes. I'm going to write a ticket specifying the final API we will implement
    to request comments before shipping ✌️️

    On Sun, Nov 20, 2016 at 9:15 PM Ari [email protected] wrote:

    Bump: Curious if there is any movement on this PR?

    —
    You are receiving this because you were mentioned.
    Reply to this email directly, view it on GitHub
    #25 (comment), or mute
    the thread
    https://github.com/notifications/unsubscribe-auth/AAAy8YazyRi1KR7WCBmcft5jYfY0KEwaks5rAOKIgaJpZM4KYHwp
    .

  25. rauchg commented on Nov 23, 2016

    @rauchg
    MemberAuthor

    Closing this in favor of "Programmatic API": #291.
    Thanks a lot for your feedback!

    Keep track of that issue to learn about the progress of its implementation.

    Closing this as it's no longer an exploration.

  26. rdewolff commented on Mar 30, 2017

    @rdewolff

    Like @rauchg mentioned, having a similar function to the "eject" of create-react-app would be great.

    It would comfort users that doubt to use Next.js because of the "closed environment".

  27. tomsoderlund commented on Aug 7, 2017

    @tomsoderlund

    Is @jmfirth's suggestion implemented, or is a custom Express server the way to implement an API (custom backend)?

  28. timneutkens commented on Aug 7, 2017

    @timneutkens
    Contributor

    Custom server is the way to go 👍

  29. locked and limited conversation to collaborators on Aug 7, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions