You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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){returnrenderComponent(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.
Reacted by swlkr, Vitaly Domnikov, David Jones, Denis Ciccale, Gio d'Amelio, Jared Palmer, Sebastian, Dan, Marius Craciunoiu, Timo Lins and 31 more
This should be fairly easy to implement. Wanted to hear comments about whether the proposed API makes sense to you all.
Reacted by Spencer, Fernando Alex Helwanger, Roman Khitin, Connor Walsh, Keith Bingman, Lobito, Tarik Fojnica, Marcel Mokoš and Nick K.
Reacted by Brian Kim, Arunoda Susiripala, Stefano Ceschi Berrini, Billy Rukh, Spencer, Fernando Alex Helwanger, Jason Nall, Dan Zajdband, Daniel O’Connor, Roman Khitin and 6 more
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) => ?
Reacted by Till, Chris Bitsakis, Roman Khitin, Ganaraj Permunda Ramakrishna and Daryl Roberts
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
@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.
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.
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.
code may need to be able to do something when both entering on a route and leaving a route
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
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.
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?
You can do this with lifecycle hooks. didMount / unmount
This is also up to react and componentWillReceiveProps, shouldUpdate, etc
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.
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.
@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
Reacted by ^_^, Mykola Bilokonsky, Vitaly Domnikov, Aegir Thor, Matias Crivolotti, Navaru, Nicolae Vartolomei, Juan Carlos Christensen, Fernando Alex Helwanger, pol and 7 more
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.
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.
Reacted by Giacomo Rebonato, Evan Tahler, rossipedia, Guillermo Rauch, Nicholas Barone, Sam, Benjamin Goering, Marcel Mokoš and Adrian Li
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).
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.
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?
Reacted by ^_^, Tim Broddin, Vlad Frolov, Peter S., Rainer Borene, Louis-André Labadie, Giacomo Rebonato and delsanic
Reacted by Fernando Alex Helwanger, Matt Tortolani, Paul Dechov and Jared Palmer
Reacted by Timo Lins, Fatih Kalifa, Fernando Alex Helwanger, Giacomo Rebonato, Nicolas Cisco, David Street, Yannik Schweinzer, Bryan Smith, Jared Palmer, Arunoda Susiripala and 3 more
Activity
nodegin commentedon Oct 25, 2016
Can't get this this to working, I have tried to create a
server.jsbut still showing 404 with no logs printed on console
dotcypress commentedon Oct 26, 2016
@nodegin this feature isn't implemented yet. 😢
@rauchg do you wanna PR for that?
rauchg commentedon Oct 26, 2016
This should be fairly easy to implement. Wanted to hear comments about whether the proposed API makes sense to you all.
malixsys commentedon Oct 26, 2016
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) => ?
jmfirth commentedon Oct 26, 2016
Without realizing this issue existed I have done some work toward this already. It allows for custom endpoints placed in an
/apifolder. Perhaps the modifications might interest someone here: jmfirth@c42b562Outline of changes:
An example endpoint
/api/hello.js:And response from
/api/hello:neb-b commentedon Oct 26, 2016
@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
diranddevvariables?jmfirth commentedon Oct 26, 2016
devis presumably a development mode flagdirappears to be an injectable root module path that defaults toprocess.cwd()A more general answer is that it follows the same general convention that the
rendermethod follows. Both seem like they could be potentially useful for someone developing endpoints.nodegin commentedon Oct 26, 2016
this should be merged into master
davibe commentedon Oct 26, 2016
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.
code may need to be able to do something when both entering on a route and leaving a route
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
sub-routes like
product/:id/comments/:cid/author?expanded=truemeans that a child component may need to access "parent" parts of the url, the data fetched by parent components, url parameters.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?jaredpalmer commentedon Oct 26, 2016
Would you allow for
renderJSONtoo?rauchg commentedon Oct 26, 2016
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 :)
rauchg commentedon Oct 26, 2016
Also, if you want to parse incoming JSON, you can just use micro tools!
I like this a lot as it preserves minimalism and great performance while allowing for unlimited power!
rauchg commentedon Oct 26, 2016
@davibe
dotcypress commentedon Oct 26, 2016
Will be nice to have method for serving static files.
12 remaining items
mbilokonsky commentedon Oct 31, 2016
Specifically, rather than adding
serversupport 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
orchestratoror 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
nextto stub that out. (or, down the line,nextcould 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/pingand returnspong, 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
nextproject 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 devto run all of your services locally on different ports (and your middleware tier can just be aware of this), or you could havenpm run deploy:devwhich deploys your services out tonowinstances with yourdevenvars set, ornpm run deploy:prodwhich deploys them with yourprodenvars sets and auto-aliases the middleware host to your alias.I've got a prototype that has started down this road, using
now-fleetto 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 thisorchestratorcan 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 formicro. 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.
rauchg commentedon Oct 31, 2016
@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
eirikurn commentedon Nov 5, 2016
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.
evantahler commentedon Nov 6, 2016
For custom routes, why abandon the core
the file system is the APIrule? 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.jswhich 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 theurlprop that is already being passed in.evantahler commentedon Nov 7, 2016
Solving my own problem (#25 (comment)) with #223
eirikurn commentedon Nov 7, 2016
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
renderComponentsupported additional context forgetInitialProps. This could be used to parameterise the page based on the url and external data (saving a potentially redundant fetch).tpreusse commentedon Nov 14, 2016
I would stick to just routing and think that rails does it well:
config/routes.rb->routes.jsroutes.jsis guaranteed to only run on the node side and is allowed to accessfs. 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:
tocan only point to files inpages(which are webpack entry points / chunks)./user/tpreussewould be routed topages/userwhich getsparams: {username: 'tpreusse'}ingetInitialProps. AdditionallygetInitialPropswould exposepath_forandurl_forwhich 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
renderComponentwork? Wouldn't it be more of arenderPage?auser commentedon Nov 21, 2016
Bump: Curious if there is any movement on this PR?
rauchg commentedon Nov 21, 2016
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:
rauchg commentedon Nov 23, 2016
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.
rdewolff commentedon Mar 30, 2017
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".
tomsoderlund commentedon Aug 7, 2017
Is @jmfirth's suggestion implemented, or is a custom Express server the way to implement an API (custom backend)?
timneutkens commentedon Aug 7, 2017
Custom server is the way to go 👍