“This is the 11th day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

preface

Next. Js is one of the most popular React frameworks for server-side rendering. It has been popular for many years and is favored by many developers.

However, with the introduction of Remix as open source, developers have become skeptical about which framework is friendlier for their applications, so in this article, I’ll compare some of the important features of next.js and Remix to help you choose the best framework.

Routing system

There are many similarities between Remix and next.js when it comes to routing. For example, they both follow a file-based reductive-form routing system and support dynamic routing.

The similarity is that in next.js, when you create a file in the /pages folder, it is automatically set to route.

pages/index.js ==> /

pages/users/index.js ==> /users

pages/users/create.js ==> /users/create
Copy the code

Remix also automatically creates routes. However, you need to create the file in the app/ Routes folder.

app/routes/index.js ==> /

app/routes/users/index.js ==> /users

app/routes/users/create.js ==> /users/create
Copy the code

Differentiated Remix routes are built on react-Router and you can use React Hooks directly, such as useParams and useNavigate. Remix, on the other hand, has built-in support for nested layouts, whereas Nest.js does not.

The data load

There are several data loading techniques in Web applications. Respectively is:

  • (SSR) Server-side rending in the Runtime Server rendering.
  • (SSG) Static Site Generation Static Generation + (ISR) Incremental Static Regeneration Incremental Static Generation.
  • (CSR) Client-side rending at Runtime Client rendering.
  • Mix server-side rendering with client-side rendering and static generation

In Next. Js, developers are free to load data from all of the above methods. For example, my blog uses SSG to render the article details page as a static resource, and new articles are generated incrementally and statically without repackaging.

You can get the data directly using the getServerSideProps method, and you can load the data from the server side at build time using getStaticProps and getStaticPath. The following code example shows how to load data using getServerSideProps.

export const getServerSideProps = async ({ params, query }) => {
  const id = params.id
  // Get the data from the ID on the URL
  // const data= await db.res.query(id)
  return {props: {id, Data}}
};

export default function age({id, data}) {
  return (
      <div>
        <h1>Id parameter on url: {id}</h1>
        <h2>{data}</h2>
      </div>
  );
}
Copy the code

In Remix, only SSR and CSR are supported.

You must export a loader to the routing page and use the useFetcher Hook to fetch data from the server rendering

import { useLoaderData } from "remix";

export let loader = async ({ params, request }) => {
const id = params.id
  // Get the data from the ID on the URL
  // const data= await db.res.query(id)
  	 return {id, data}
  };

export default function Page() {
  let {id, dataLimit} = useLoaderData();
  return (
        <div>
          <h1>Id parameter on url: {id}</h1>
        	<h1>{data}</h1>
        </div>
  );
}
Copy the code

Next.js supports server-side rendering (SSR), static site generation (SSG), incremental static generation (ISR), and CSR (client-side rendering). By contrast, Remix only supports SSR and CSR.

Use Sessions and cookies

There are no built-in functions in next.js that directly manipulate cookies. But popular libraries like cookie.js can be used with nextauth.js or Nextauth.js, for example, to store user authentication data in cookies.

Remix supports cookie manipulation out of the box. You can generate cookies by calling functions, and then serialize or parse the data to store or read it.

The following code snippet from Remix shows how to create logical functions in Remix to manage browser cookies.

import { createCookie } from "remix";

const cookie = createCookie("cookie-name", {
  expires: new Date(Date.now() + 60),
  httpOnly: true.maxAge: 60.path: "/".sameSite: "lax".secrets: ["s3cret1"].secure: true
});
Copy the code

style

In terms of style, Remix is slightly different from Next-js. Remix provides a built-in technique for dynamically adding styles using the links method, while next.js supports Styled-JSX as a CSS in JS scheme or uses CSS Modules, where global styles can only be written in the outermost layer of app.js

function Home() {
	return (
		<div className="container">
  	<h1>My Cart in Next.js</h1><p>Some paragraph</p><style jsx>
    	{'
      .container {
        margin: 20px;
      }
      p {
        color: blue;
      }
    `}
   </style></div>)}export default Home
Copy the code

Remix uses an easy way to add styles to a page, using the tag. The following code snippet shows how to use the links function to load the stylesheet in Remix.

export function links() {
	return [{
      rel: "stylesheet".href: "https://test.min.css"}]; }Copy the code

With the above code, link is automatically loaded and unloaded from the page.

The form

Next.js is not built in and requires ajax handling.

Remix provides built-in form functionality by replacing

export async function action({ request }) {
  let formData = await request.formData();
  let action = formData.get("_action");
  switch (action) {
    case "update": {
      // do your update
      return updateProjectName(formData.get("name"));
    }
    case "delete": {
      // do your delete
      return deleteStuff(formData);
    }
    default: {
      throw new Error("Unexpected action"); }}}export default function Projects() {
  let project = useLoaderData();
  return (
    <>
      <h2>Update Project</h2>
      <Form method="post">
        <label>
          Project name:{" "}
          <input
            type="text"
            name="name"
            defaultValue={project.name}
          />
        </label>
        <button type="submit" name="_action" value="create">
          Update
        </button>
      </Form>

      <Form method="post">
        <button type="submit" name="_action" value="delete">
          Delete
        </button>
      </Form>
    </>
  );
}
Copy the code

Deployment of 5.

Next. Js can be installed and run on any server, and it supports serverless mode. The Netlify team is also writing adaptations for Serverless.

Remix can also run on any platform and interface with any system. Therefore, Remix is an HTTP server request handler that allows you to use any server. When you build a Remix application, you are asked where you want to deploy it, and as of this writing, the following options are available:

  • Remix App Server
  • Express Server
  • Netlify
  • Cloudflare Pages
  • Vercel
  • Fly.io
  • Architect (AWS Lambda)

Horizontal contrast

Next.js Remix
SSG Static site generation ✅ built-in Does not support
SSR server side rendering ✅ built-ingetServerSideProps ✅ 通过 loader
API routing ✅ pages/API/directory Remix is routing, and you have more flexibility to customize routes
Forms the form The built-in ✅ is built-in and powerful
File system-based routing management ✅ page level ✅ component-level
Session management The built-in ✅ Built-in cookies and Sessions
Disable the JS Insufficient support was provided ✅ Static page routing
style ✅ provides global and component-level styling support for TailwindCSS, etc Routing level CSS loading and unloading
Nested layout Does not support ✅ built-in
I18n internationalization ✅ built-in The built-in
Image optimization ✅ Through the next/image component ✅ through simple conversion, alternative quality, etc
Google AMP ✅ built-in The built-in
The adapter Node.js Request and Response interfaces Fetch API Interface for Request and Response
Preload Links automatically The automatic
Exception handling Create pages such as 404,500 Use the ErrorBoundary component to throw local errors
Polyfill Fetch, Object.assign, and URL fetch

summary

Application scenario Next-js

Static websites. This is one of its biggest advantages, as Tailwind CSS allows for more flexibility in creating beautifully styled pages and components with a complete ecosystem.

Suitable for quick start projects.

Remix

In the administrative background, data loading, routing of nested data or components, and concurrent loading are optimized, and exception handling has been refined to the local level.

Maybe it’s the next generation of Web development frameworks.

Overall, Remix is a powerful framework that will become more common in 2022. However, when dealing with production-grade applications, using next.js would be the obvious choice, since it is already established and supported by the community.

reference

  • The future of websites: Next. Js and Remix
  • Remix vs. Next.js: A Detailed Comparison

This paper mainly translates the above articles, but the above articles are not comprehensive, SO I have made modifications and supplements.

That’s all the content of this article. I hope this article is helpful to you. You can also refer to my previous articles or share your thoughts and experiences in the comments section.

Recommended reading

“Say ByeBye to the loading interface” — Remix subversive preloading parsing