This Dot Blog
This Dot provides teams with technical leaders who bring deep knowledge of the web platform. We help teams set new standards, and deliver results predictably.
![Introduction to Remix cover image](https://images.ctfassets.net/zojzzdop0fzx/1epA4lWh5ijnGQwPOMhpzP/a0a5aa13c5c4fd4cb1c4d0d2642d5280/Screenshot_2021-12-14_1.10.21_PM.png?fm=webp&w=3840&q=75)
Introduction to Remix
What is Remix? Remix is a full stack web framework based on web fundamentals and modern UX. It was created by the Remix.run team, founded by Ryan Florence and Michael Jackson. They are the creators of React Router. Remix is a seamless server and browser runtime. It has no static site support, and always relies on a server. Remix aims to provide fast page load times and instant UI transitions. Remix is built on the Web Fetch API, which allows it to run anywhere. It can be deployed in a serverless environment or in a Node.js server environment. Remix features Fast data fetching Fetching data is so fast with Remix that there is no need for transitional spinners. Rather than fetching data via a series of requests from components, Remix will load data in parallel on the server. It will then send the browser an HTML document that contains the data, ready to be displayed. Making use of its own cache, Remix makes page reloads really fast. Remix will reload unchanged data from the cache, and only fetch new data. Forms Remix has a Form component, which is an enhanced HTML form component. Remix's Form component requires no onChange, onClick, or onSubmit events on the form or its fields. Contrary to traditional React forms, there is also no need for useState fields per form input. Remix's Form component will automatically do a POST request to the current page route with all the form's data submitted. It can be configured to do PUT and DELETE requests as well. To handle requests from a form, a simple action method is needed. Forms have traditionally been a point of frustration with React apps. Remix's approach to forms allows developers to create forms without having to write lines and lines of boilerplate code. Routing Similar to Next.js, Remix uses the file system to define page routes. Remix is built on top of React Router v6. This means that all the React Router APIs can be used in a Remix application. Anything that works with React Router will work within Remix. When navigating using a Link tag, the Outlet tag from React Router will automatically render the link's content on the page. This makes it easy to build a hierarchy of nested routes. Nested routes Nested routes allow Remix to make apps really fast. Remix will only load the nested routes that change. Remix will also only update the single nested component that was updated by some user interaction. Nested Routes also provide nested CSS styling. This allows CSS to be loaded on a per page basis. When a user navigates away from a certain page, that page's stylesheet is removed. Error handling When a route in a Remix app throws an error in its action method, loader, or component, it will be caught automatically. Remix won't try to render the component. It will render the route's ErrorBoundary instead. An ErrorBoundary is a special component that handles runtime errors. It's almost like a configurable try/catch block. If a given route has no ErrorBoundary, then the error that occured will bubble up to the routes above until it reaches the ErrorBoundary of the App component in the root.tsx file (assuming TypeScript is used). Error handling is built into Remix to make it easier to do. If an error is thrown on the client side or on the server side, the error boundary will be displayed instead of the default component. This graceful degradation improves the user experience. Project setup Creating a new Remix project is as easy as using the following command in a terminal window. ` You'll be asked to pick a folder name for your app. You'll also be asked where you want to deploy. Select *Remix App server*. > Remix can be deployed in several environments. The "Remix App Server" is a Node.js server based on Express. It's the simplest option to get up and running with Remix. You'll then be asked to choose between TypeScript or JavaScript. The last step will ask you if you want to run npm install. Say yes. Once installed, Remix can be run locally by using the following terminal commands. ` Once Remix is running, you can go to localhost:3000 in your browser to see if the default Remix installation worked. You should see the following. Project structure Let's explore the project structure that Remix created for us. - The public/ folder is for static assets such as images and fonts. - The app/ folder contains the Remix app's code. - The app/root.tsx file contains the root component for the app. - The app/entry.client.tsx file runs when the app loads in the browser. It hydrates React components. - The app/entry.server.tsx generates a HTTP response when rendering on the server. It will run when a request hits the server. Remix will handle loading the necessary data and we must handle the response. By default, this file is used to render the React app to a string/stream that is sent as a response to the client. - The app/routes/ folder is where *route modules* go. Remix uses the files in this folder to create the URL routes for the app based on the naming of these files. - The app/styles/ folder is where CSS goes. Remix supports route-based stylesheets. Stylesheets that are named after routes will be used for those routes. Nested routes can add their own stylesheets to the page. Remix automatically prefetches, loads, and unloads stylesheets based on the current route. - The remix.config.js file is used to set various configuration options for Remix. > Any file ending with .client.* or .server.* is only available on the client or the server. Demos The default installation of Remix comes with demos that allow us to see some of Remix's defining characteristics in action. Forms and actions Head over to http://localhost:3000 in your browser. Click on the Actions link under the Demos In This App heading. This will give you a chance to try out Remix forms and their corresponding action methods. To view the code for this demo, take a look at the app/routes/demos/actions.tsx file. ` The action function above is a server-only function to handle data mutations. If a non-GET request is made to the page's route (POST, PUT, PATCH, DELETE), then the action function is called before the loader function. Actions are very similar to loaders. The only difference is when they are called. CSS and Nested routes Click on the Remix logo to go back to the welcome page. Now, click on Nested Routes, CSS loading/unloading to see how Remix allows certain CSS rules to only be included on specific routes and their children. To view the code for this demo, take a look at the files in theapp/routes/demos/about/ folder, as well as the app/styles/demos/about.css file for the route-based CSS. Linking to a nested page is as simple as: ` Linking back to a parent route from a nested route is as simple as: ` Routing and Error Boundaries Click on the Remix logo to go back to the welcome page. Now, click on URL Params and Error Boundaries to see how routing and error boundaries work in Remix. To view the code for this demo, take a look at theapp/routes/demos/params/$id.tsx file. Loader This route defines a *loader* function that is called on the server before providing data to the route. When a route needs to fetch data from the server, Remix uses the loader function to handle that responsibility. The loader function aims to simplify the task of loading data into components. Contrary to Next.js, API routes are not needed to fetch data for route components in Remix. Here is the loader function above the ParamDemo component. ` The ParamDemo component uses a useLoaderData hook to get the data from the loader function. In this case, that data is the id value of the URL parameter that is passed to the route. Error Boundary ` An ErrorBoundary component is rendered when an error occurs anywhere on the route. Error boundaries are helpful for uncaught exceptions that we don't expect to happen. Clicking on the *This one will throw an error* link will trigger the ErrorBoundary. Catch Boundary ` A CatchBoundary component is rendered when the loader throws a Response. The status code of the response can be checked from within the CatchBoundary by using the useCatch hook. Clicking on the *This will be a 404* and *And this will be 401 Unauthorized* links will trigger the CatchBoundary. Conclusion Remix is backed by some of the most talented engineers in the React community. Version 1.0 of this full stack React-based web framework was just released on November 22, 2021. It's now released under the MIT license and is open source, making it free to use. For more Remix tutorials, check out the following: - Developer blog - Jokes App...
Jan 4, 2022
7 mins
![Building full-stack React apps with Next.js API routes cover image](https://images.ctfassets.net/zojzzdop0fzx/7vklMNIxT0dOOZ1eBhx6cz/4f37c58da0084e36e237fe44509eb336/Screenshot_2021-12-02_1.02.54_PM.png?fm=webp&w=3840&q=75)
Building full-stack React apps with Next.js API routes
Besides Next.js being a great front-end framework for React, it also provides a simple way to build an API for your front-end - all in the same web app! As of version 9, Next.js provides API routes that allows developers to create API endpoints using the Next.js folder structure. We can use API endpoints to build either a RESTful API, or a GraphQL API. This article will focus on a RESTful API for the sake of simplicity. With Next.js API routes, there's no longer a need to set up a back-end Node.js server to build an API. Building out two separate projects for the front-end and back-end of an application introduces its own set of challenges. Next.js simplifies this process by becoming a full-stack web framework with the addition of API routes. Building and deploying a full-stack web app has never been faster and easier! Setting up API routes API routes go in the pages/api directory of a Next.js project. When a file or folder is added to this pages/api folder, Next.js will create an API endpoint URL for it. Creating a pages/api/users.ts file will create an /api/users API endpoint. We can also create an /api/users API endpoint by creating a pages/api/users/index.ts file. To create a dynamic API route for a specific user, we can create a pages/api/users/[id].ts file. This dynamic route will match requests such as /api/users/1. Just like the pages folder maps its files and folders to URLs that can be visited in a web browser, the pages/api folder maps its files and folders to API endpoint URLs. Creating API routes To begin, let's create a new Next.js project called nextjs-full-stack. ` If you prefer using TypeScript with Next.js, you can use npx create-next-app --ts instead. For this article, we'll just use JavaScript. Notice that newly created Next.js project contains a pages/api/hello.js file. An /api/hello API endpoint has already been provided for us. Let's run the project using npm run dev to try this API endpoint. Visit http://localhost:3000/api/hello in a web browser. You should see the following response. ` Understanding API routes Let's take a look at the code in the pages/api/hello.js file. ` The default export in files that are found within the api folder must be a function. Each function is a handler for a particular route. Asynchronous functions are also supported for cases where requests need to be made to external APIs or a database. When running the Next.js project locally, it creates a Node.js server and passes the request and response objects from the server into the handler function of the requested endpoint. A dynamic route Let's create a pages/api/users/[id].js file to create an API route for a specific user. Let's add the following code within this file. ` For the purposes of creating an example, we mocked up a list of users within the file. More realistic usage might involve querying a database for the requested user. The id value is retrieved from the request query parameter, and then used to find the corresponding user object in the list of users. Keep in mind that the id from the request is a string, so we must parse it to an integer in order to perform a user lookup by id on the users list. Visit http://localhost:3000/api/users/1 in a web browser. You should see the following response. ` Returning an error We can modify the user endpoint we just created to return an error when the requested user id is not found in a list of users. ` Visit http://localhost:3000/api/users/3 in a web browser. You should see the following response since no user with an id of 3 exists. ` Handling multiple HTTP verbs Next.js API routes allow us to support multiple HTTP verbs for the same endpoint all in one file. The HTTP verbs that we want to support for a single API endpoint are specified in the request handler function. Let's create a pages/api/users/index.js file to create an API route for all users. We want this endpoint to support GET requests to get all users and POST requests to create users. Let's add the following code within this file. ` The req.method value will tell us what HTTP verb was used to make the request. We can use a switch statement to support multiple HTTP verbs for the same endpoint. Any HTTP requests that are not GET or POST, requests will enter the default case and return a 405 Method Not Allowed error. Visit http://localhost:3000/api/users in a web browser. You should see the following response. ` We can use an API platform like Postman or Insomnia to test POST, PUT, and DELETE requests to this API endpoint. Testing the POST request will return the following response. ` Testing PUT and DELETE requests will return Method Not Allowed errors with a 405 Method Not Allowed response code. Using API routes from the front-end Let's create a users/[id].js page to retrieve a specific user when the page loads, and then mimic a save profile operation when the form on the page is submitted. We will use client-side rendering within Next.js for this page. Client-side rendering is when the client makes requests for API data. The approach used in this example can also apply for pages that use server-side Rendering (SSR). ` To retrieve a user by id when the page loads, we can use the React useEffect hook with the id as a dependency. The browser-supported Fetch API is used to make a GET request to /api/users/[id]. Async/await is used to wait for this asynchronous request to complete. Once it is completed, the user's name is saved to the component state using setName, and displayed within the input text box. When the form is submitted, a POST request is made to the /api/users API route that we created earlier. To keep things simple, the response of the request is then logged to the console. Conlusion Next.js makes it fast and easy to build an API for your next project. A very good use case to get started with Next.js API routes is for the implementation of CRUD operations to handle form input. API endpoints are created as Node.js serverless functions. You can build out your entire application's API with Next.js API routes. Go ahead and build something awesome with them!...
Dec 17, 2021
5 mins
![Next.js Conf 2021 Highlights cover image](https://images.ctfassets.net/zojzzdop0fzx/4S8qaGksUpabym1XVc5I9k/3bd76bf6a6238916c0a79b5560c3fa46/Screenshot_2021-11-12_12.28.15_PM.png?fm=webp&w=3840&q=75)
Next.js Conf 2021 Highlights
Given how well-presented it was, it's hard to believe that Next.js Conf 2021 was only the second edition of Vercel's Next.js Conf. Vercel is the creator of the industry-leading React and JavaScript framework for full-stack web development called Next.js. This year also marked a milestone birthday celebration for Next.js as it turned 5 years old. Guillermo Rauch, CEO of Vercel and co-creator of Next.js, started off the conference with a keynote talk. Guillermo announced Next.js version 12, the biggest release ever. Guillermo highlighted the following features of Next.js 12. A new Rust-based compiler Next.js 12 uses a Rust compiler built with SWC, which stands for Speedy Web Compiler. It's an open platform for fast tooling. This compiler improves both local and production environments. This new Rust-based compiler achieves around 5 times faster builds and around 3 times faster Hot Module Replacement (or HMR). Zero code updates are required to benefit from these improvements. Simply update your Next.js app to version 12 to begin enjoying the benefits of this new compiler. ES Modules Next.js 11.1 added experimental support for ES modules. In Next.js 12, ES modules are now the default. ES modules are the official, standardized module system for JavaScript. They are supported by all major browsers and Node.js. This standardized module system allows for smaller package sizes. URL Imports Next.js 12 includes experimental support for URL Imports. This allows developers to use any package directly via a URL. There is no install or build step required. Remote resources can be processed exactly like local dependencies. Middleware & Edge Functions Over the past few years, Next.js has provided tremendous support for serverless deployments, thereby eliminating the DevOps burden for developers. Next.js continued on this mission by introducing *middleware* and *edge functions* on Vercel serverless deployments. Middleware Next.js middleware allow developers to run code before a request is completed. The response to an incoming request can be modified by rewriting, redirecting, adding headers, or streaming HTML. This allows middleware to be used for things like authentication, feature flags, A/B testing, logging, server-side analytics, and more. Next.js middleware provide the same flexibility on serverless platforms that is available with traditional web servers. Next.js middleware support Web APIs like fetch and they work out of the box in Next.js 12, or deployed as edge functions on Vercel. Edge functions Edge functions allow developers to run code close to their users. Vercel now supports edge functions for all users on their platform. It's important to note that other hosting providers can also be configured to support middleware at the edge, and not just Vercel. Multi-region deployment is often avoided due to cost and complexity. With edge functions, server-side logic can now be moved to the Edge, close to the geographic location of the website visitor. This results in improved loading times for visitors, no matter where they visit from. As developers, we typically serve dynamic content for visitor personalization reasons and serve static content for faster load times. However, with a Next.js middleware deployed as an edge function, dynamic content can be served at the speed of static content. Edge functions help to solve the common issues with serverless deployments because they boot up instantly, deploy globally, and support streaming data. The future of React Next.js 12 brings the future of React to Next.js. It includes experimental support for React 18 and React server components. It was reassuring to hear how closely Next.js is working with the React team to prepare Next.js for React 18, server-side streaming, and React server components. React server components React server components allow individual components to be rendered on the server-side. It's different from *Server-Side Rendering (SSR)*, which pre-generates the HTML of an entire web page on the server. Server-Side Rendering renders all the HTML on the page or nothing at all. With React server components, a web page can progressively update at the component level as data comes in. With React server components, data fetching can be done at the component level. This simplifies things, because getServerSideProps and getStaticProps will no longer be needed. This aligns more closely to the React hooks model, which advocates for combining data fetching with components. Using server components React server components can be used in Next.js 12 with an experimental flag. To try out React server components, we can simply give any page a .server.js or .server.ts suffix. Client-side rendered components can be used within the server component. These client components will hydrate and become interactive when the server component is rendered. This can be useful for adding client-side functionality to a page, like upvoting and downvoting behaviors. Benefits of server components React server components require no client-side JavaScript and they improve page rendering speeds, as well as the user experience. React server components provide greater flexibility, allowing the developer to choose where a component renders, either on the client or on the server. Granular component caching The Next.js team showcased a new exploration that is currently underway using a new Data component that works like a React suspense boundary. This new component supports granular component caching. It's similar to *Incremental Static Regeneration (ISR)*. Next.js Analytics Last year, Next.js announced Next.js Analytics to help monitor web vitals. Since then, it has seen amazing adoption, processing over 7 billion data points. This year, Next.js announced Checks, automated performance checks that start automatically and report results when a deployment finishes. A preview deployment is checked to ensure that there are no runtime errors and that good performance makes its way into production. This is all thanks to the end-to-end reliability checks and *Web Vitals* performance checks that are done. Next.js Live During the conference, we learned about the evolution of Next.js Live, which was presented at last year's Next.js Conf. Next.js Live provides an instant development and real-time collaboration experience for Next.js. All it takes to collaborate with Next.js Live is a link. Next.js Live makes it possible to code, chat, draw, and edit, directly from a web browser. Next.js Live now provides new Git integrations. Next.js Live runs natively in web browsers, and now boots up instantly thanks to innovations like ES Modules and Web Assembly, which the new compiler takes advantage of. Notable Talks Next.js 12 Overview Developer Experience of the Future by Lee Robinson. Learn more about the features included in Next.js 12. Edge functions Next.js at the Edge by Suzanne Aldrich and Lee Robinson. Learn more about Edge functions with Next.js and Vercel. Edge Functions Explained by Kelsey Hightower and Lee Robinson. See a demo of edge functions and learn how they're different from the traditional way of building for the web. Next.js and databases Next.js and Prisma: Databases in Serverless Made Easy by Daniel Norman. Learn how Prisma makes building database-driven applications with Next.js a breeze. Streaming Streaming in Next.js by Kara Erickson. Learn about the benefits of streaming with Next.js. Getting Started Getting Started with Next.js by Delba de Oliveira. Learn the fundamentals of React and Next.js. All Talks To view all the talks that were part of Next.js Conf 2021, visit the Vercel YouTube page....
Nov 18, 2021
6 mins
![Introduction to RESTful APIs with NestJS cover image](https://images.ctfassets.net/zojzzdop0fzx/2mMFrC7KPsteZ6G90SfEg0/b2479be831d8febe3485dd4d8fc0ee65/Screenshot_2021-09-13_1.05.20_PM.png?fm=webp&w=3840&q=75)
Introduction to RESTful APIs with NestJS
Introduction on RESTful API with NestJS, covering topics such as module organization, service and controller implementation, testing with Insomnia, logging, Swagger documentation, and exception handling....
Sep 15, 2021
13 mins
Let's innovate together!
We're ready to be your trusted technical partners in your digital innovation journey.
Whether it's modernization or custom software solutions, our team of experts can guide you through best practices and how to build scalable, performant software that lasts.