简体   繁体   English

我必须在 Next.js 项目中使用 express 吗?

[英]Do I have to use express in Next.js project?

I'm making a website via Next.js .我正在通过Next.js创建一个网站。 Next.js provides SSR and dynamic routing . Next.js提供SSRdynamic routing

  • Do I have to use express ?我必须使用express吗?
  • If so, why do I have to use it?如果是这样,为什么我必须使用它?
  • What kind of features of express are useful that are not provided from Next.js ? Next.js没有提供哪些express功能有用?

I think next build & next start show pages as well as I expected.我认为next buildnext start显示页面和我预期的一样。

You do not need to use express, Next JS already has its own built-in server.你不需要使用 express,Next JS 已经有自己的内置服务器。 However since express is popular, it is easier for developers to communicate with databases or handle other backend work.然而,由于 express 很受欢迎,开发人员更容易与数据库通信或处理其他后端工作。

Both, Next.js and Express.js are server side render solutions (SSR). Next.js 和 Express.js 都是服务器端渲染解决方案 (SSR)。 However, you can integrate Next.js with Express.js with a custom server api, as stated in the documentation:但是,您可以将 Next.js 与 Express.js 与自定义服务器 api 集成,如文档中所述:

Most of the time the default Next.js server will be enough but there are times you'll want to run your own server to integrate into an existing application.大多数情况下,默认的 Next.js 服务器就足够了,但有时您需要运行自己的服务器以集成到现有应用程序中。 Next.js provides a custom server api . Next.js 提供自定义服务器 api

const express = require("express");
const next = require("next");

const port = 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.get("/test", (req, res) => {
    return app.render(req, res, "/test");
  });
  
  server.get("*", (req, res) => {
    return handle(req, res);
  });

  server.listen(port, (err) => {
    if (err) throw err;
    console.log(`Ready on http://localhost:${port}`);
  });
});

In example, it's showed how to use get Express method to handle routes in a Next.js app.例如,它展示了如何使用get Express 方法来处理 Next.js 应用程序中的路由。 The code above will render the React component at./pages/test.js when user points to http://localhost:3000/test and pass down req and res objects to render.当用户指向http://localhost:3000/test并传递reqres对象进行渲染时,上面的代码将在 ./pages/test.js 处渲染 React 组件。

  • Do I have to use express?我必须使用快递吗? - If you will deploy it via Now, you dont have to. - 如果您将通过 Now 部署它,则不必这样做。 But if you are going to host it somewhere else, then yes.但是,如果您要将其托管在其他地方,那么可以。
  • If so, why do I have to use it?如果是这样,为什么我必须使用它? - Express is the one that serves the SSRed pages. - Express 是为 SSRed 页面提供服务的一种。
  • What kind of features of express are useful that are not provided from Next.js? Next.js 没有提供哪些 express 功能有用? Next.js is used in conjunction with either a Serverless server (Now) or by Express. Next.js 与无服务器服务器(现在)或 Express 结合使用。 These two are your options to serve your Next.js Application.这两个是您为 Next.js 应用程序提供服务的选项。

Answer:回答:

  • You do not need to use express to use nextJS out of the box;您无需使用express即可使用 nextJS 开箱即用; the vast majority of people don't.绝大多数人没有。

Long Answer:长答案:

If you are not hosting on Vercel's platform, for example self-hosting (AWS,Digital Ocean, Azure etc...) you optionally have the ability to define a custom nextjs server and swap the underlying server.如果您不在 Vercel 的平台上托管,例如自托管(AWS、Digital Ocean、Azure 等),您可以选择定义自定义 nextjs 服务器并交换底层服务器。

When might a custom server be a good idea?什么时候定制服务器是个好主意?

  • when you're not hosting on vercel当您不在 vercel 上托管时
  • when you have custom requirements & custom existing infrastructure.当您有自定义要求和自定义现有基础架构时。

Scenario: Imagine a large company with lots of custom built infra (logging, AB testing, custom linters etc) they've built over the years ( linkedin, netflix, any company really... ).场景:想象一个大公司,他们多年来建立了许多定制的基础设施(日志记录、AB 测试、定制 linter 等)( linkedin、netflix、任何公司…… )。 They now want to take advantage of some of NextJS abstractions like:他们现在想要利用一些 NextJS 抽象,例如:

  • different SSR rendering strategies不同的 SSR 渲染策略
  • modern/flexible build system现代/灵活的构建系统
  • all the other stuff you would need to implement from scratch, maintain, test...您需要从头开始实施,维护,测试的所有其他东西......

Let's call this company XCompany.我们称这家公司为 XCompany。 XCompany uses ExpressJS ( doesn't matter which node server/framework ) for their web server. XCompany 为他们的 web 服务器使用 ExpressJS(不管哪个节点服务器/框架)。 They want to continue using ExpressJS since they've invested lots of time, resources building custom infrastructure and tools to work with it like AB testing integration, logging middlewares etc.他们希望继续使用 ExpressJS,因为他们已经投入了大量时间、资源来构建自定义基础架构和工具,例如 AB 测试集成、日志中间件等。

A custom server would allow XCompany to continue using Express without a monumental change and still benefit from the stuff NextJS is great at like SSR, the build system etc, nice conventions & guardrails etc.自定义服务器将允许 XCompany 继续使用 Express 而无需进行重大更改,并且仍然受益于 NextJS 擅长的东西,如 SSR、构建系统等、良好的约定和护栏等。

When you self-host your sever and deploy it to your on infrastucture you get a long running node server, which is different from hosting on vercel, where the server is a serverless function.当您自行托管服务器并将其部署到您的基础设施时,您将获得一个长时间运行的节点服务器,这与在 vercel 上托管不同,后者的服务器是无服务器 function。

Context/History背景/历史

NextJS under the hood uses vanilla HTTP server. NextJS 在后台使用 vanilla HTTP 服务器。 If you would like to get similar express functionality like the way routes are setup/organized you can use a package like next-connect .如果您想获得类似的express功能,例如设置/组织路线的方式,您可以使用 package 之类next-connect

Express use to rely on the connect package. Express 使用依赖于connect package。 Most nodejs servers follow connect like API for routing & setting up handlers.大多数 nodejs 服务器都遵循connect ,如 API 用于路由和设置处理程序。

For folks coming outside of the NodeJS world (python/flask), the connect style of organizing server routes is sort of like WASGI - Web Server Gateway Interface in philosophy, but there is no spec or anything like that.对于来自 NodeJS 世界(python/flask)之外的人来说,组织服务器路由的连接方式有点像WASGI - Web 服务器网关接口在哲学上,但没有规范或类似的东西。

Cons/Challenges of using Custom NextJS Server?使用自定义 NextJS 服务器的缺点/挑战?

  • initial time investment learning custom nextJS server patterns .初次投资学习自定义 nextJS 服务器模式 The vast majority of people don't go down this route绝大多数人不会走这条路
  • you can't deploy custom servers to vercel , but if you went down this route you're likely not going您无法将自定义服务器部署到 vercel ,但如果您沿着这条路线走,您可能不会去
  • if you're not hosting on vercel you don't get serverless functions .如果您不在 vercel 上托管,您将无法获得无服务器功能 This may not be con or downside, if you don't have a serverless use case.如果您没有无服务器用例,这可能不是缺点或缺点。
    • For example, if you're web server will be using websockets/WebtRTC which require persistent long running connections between client and server than serverless function's arent the best choice here;例如,如果您是 web 服务器将使用 websockets/WebtRTC,这需要客户端和服务器之间持久的长时间运行连接,而不是无服务器功能不是这里的最佳选择; there are work arounds, but i still think its not the best use case.有解决方法,但我仍然认为它不是最好的用例。 Note, you can still use add on serverless features to your custom server through another provider (AWS, Azure, etc...)请注意,您仍然可以通过其他提供商(AWS、Azure 等)向您的自定义服务器添加无服务器功能

Moving Forward Most js runtimes have been converging on exposing & using the Request &Response object APIs and exposing them to consumers.向前发展大多数 js 运行时都在公开和使用RequestResponse object API 并将它们公开给消费者。

Note, there's a ton of stuff that could be talked about here.请注意,这里有很多东西可以讨论。 Please leave follow up questions & I will try to update this answer accordingly请留下后续问题,我将尝试相应地更新此答案

Resource(s)资源)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM