#NextJS component library
Explore tagged Tumblr posts
justnshalom · 6 months ago
Text
Building a Component Library for NextJS: A Guide to Reusable UI
Building a Component Library for NextJS: A Guide to Reusable UI Have you ever found yourself rewriting the same UI components over and over again in your NextJS projects? Have you struggled to maintain consistency and efficiency across multiple applications? If so, it’s time to consider building a component library. A component library is a collection of reusable UI elements that can be shared…
0 notes
itlabour · 2 months ago
Video
youtube
How Mantine UI Can Help You Build Apps 5X Faster | 2025
Looking for the fastest way to build stunning web apps? Mantine UI can help you build apps 5X faster with its powerful, customizable, and developer-friendly components. In this video, we explore why Mantine UI is gaining massive popularity among React developers and how you can use it to speed up your projects.
From ready-to-use components to advanced theming options, Mantine UI is designed for both beginners and pros. Whether you’re creating dashboards, landing pages, or full-scale applications, Mantine UI gives you the flexibility and performance you need.
🔥 Key Highlights: ✔️ What makes Mantine UI unique? ✔️ Hands-on demo of Mantine components. ✔️ How Mantine UI compares to other UI libraries. ✔️ Best practices for seamless UI design.
Don’t miss out—watch now and start building faster with Mantine UI! 🚀
🔔 Subscribe for more web development tips & tricks!
🔥 Hashtags
#MantineUI #ReactJS #WebDevelopment #UIDesign #Frontend #ReactComponents #OpenSource #JavaScript #NextJS #TechTrends
🔑 SEO Tags
Mantine UI, Mantine UI tutorial, Mantine UI React, best React UI library, React UI components, how to use Mantine UI, Mantine UI vs Material UI, Mantine UI vs Chakra UI, best UI library for React, React component library, React UI framework, UI design in React, front-end development, build React apps faster, React UI templates, React theming, responsive UI with Mantine, web development 2025, modern UI frameworks, free React UI components, open-source UI library, Mantine UI review, best UI kit for React, Mantine UI examples, Mantine UI customization, UI/UX with Mantine, front-end tools for developers, how to style React apps, developer productivity tools, speed up UI development, React UI best practices, Mantine UI pros and cons
0 notes
inwizardssoftwaretechnology · 11 months ago
Text
ReactJS vs. Next.js: Which is Best for Web Development?
Tumblr media
When starting with web development, choosing the right framework can be a bit overwhelming. Let’s break down the basics of ReactJS and Next.js to help you decide which one suits your needs.
What is ReactJS?
ReactJS is a popular JavaScript library for building user interfaces, especially single-page applications. It’s maintained by Facebook and a community of developers. Here’s why ReactJS might be the right choice for you:
Component-Based: Build encapsulated components that manage their own state.
Reusable Components: Reuse components to build complex UIs.
Virtual DOM: Efficient updates and rendering of components.
What is Next.js?
Next.js is a React framework that adds more features and functionalities, making it easier to build production-ready applications. It’s developed by Vercel. Here’s why you might consider Next.js:
Server-Side Rendering (SSR): Improve performance and SEO by rendering pages on the server.
Static Site Generation (SSG): Pre-render pages at build time for faster load times.
API Routes: Create backend endpoints without needing a separate server.
Key Differences Between ReactJS and Next.js
Rendering Methods:ReactJS: Client-Side Rendering (CSR) by default.Next.js: Supports SSR, SSG, and CSR.
Routing:ReactJS: Needs a third-party library like React Router.Next.js: Built-in file-based routing.
Development Experience:ReactJS: More control and flexibility; requires more setup.Next.js: Out-of-the-box features for a smoother development experience.
When to Use ReactJS?
You need a highly interactive UI: Perfect for dynamic, single-page applications.
You want full control over your setup: Great if you enjoy customizing your development environment.
You’re working on a smaller project: Easier to manage without the overhead of a full framework.
When to Use Next.js?
SEO is crucial: SSR and SSG improve search engine rankings.
You want faster load times: Static generation helps with performance.
You prefer an all-in-one solution: Built-in routing and API handling streamline development.
Conclusion
Choosing between ReactJS and Next.js depends on your project needs. For a dynamic, highly interactive application with custom setups, ReactJS is ideal. For a fast, SEO-friendly, and production-ready app, Next.js is the way to go.
Looking for a reliable partner to bring your Web Development vision to life? Look no further than Inwizards Software Technology! Our expert team specializes in creating dynamic, responsive, and scalable web solutions tailored to your business needs. Whether you need a sleek website, a robust e-commerce platform, or a custom web application, we’ve got you covered.
Let’s transform your ideas into reality. Contact Inwizards Software Technology today and take the first step towards digital excellence!
Visit our website to learn more and get in touch with us: Inwizards Software Technology
Read our blog — https://www.inwizards.com/blog/nextjs-vs-reactjs/
0 notes
glorywebs-usa · 6 months ago
Text
ReactJS vs NextJS: Which Framework Should You Choose in 2025?
Tumblr media
Two web application development frameworks that jump in one's thoughts are ReactJS & NextJS. Each has its own advantages and has been adopted by many developers all around the world. This blog post will discuss the debate of ReactJS vs NextJS so you can better determine what fits your project needs. Let's go over each framework, look at their features, and then see how to choose between them.
Understanding ReactJS
A library developed by Facebook (now Meta) with a focus on making user interfaces has attracted much attention since its release. React is lightweight, efficient, and reusable, making it one of the most popular libraries in the industry today. With React, you can create dynamic user interfaces by breaking down complex components into smaller, reusable parts, which are easy to manage and can be used repeatedly in different parts of the application.
Key Features of ReactJS
Component-Based Architecture: React JS utilizes a component-based structure, and developers can create encapsulated components that maintain their own state. This way modularity is improved and code reuse increases.
Virtual DOM: The virtual DOM of React optimizes the rendering of the UI, reducing duplicate updates. Thus, this makes the React-based applications faster and interactive.
Strong Community Support: You have a large number of developers for the ReactJS solution; thus, it is easy to find resources, tools, or a development company that focuses on ReactJS.
ReactJS is great if you are more interested in more interactive UIs, or want maximum flexibility in structuring your web application. This is particularly ideal if building a single-page application that doesn't necessarily benefit from server-side rendering.
Introduction to NextJS
NextJS is a React framework that is developed by Vercel. It expands on top of everything that is possible inside of React to offer more tools and conventions, especially around server-side and static site generation. The combination brings ease of use within React with scalability in server-side rendering, so faster page loads and good SEO are achieved. While ReactJS is strictly only about client-side code, NextJS is born to ease full-stack development by handling both client- and server-side code.
NextJS: Important Features
Server-Side Rendering (SSR): Server-side rendering is made much more elegant using NextJS. It ensures that the initial page load is faster, and all the optimistic outputs in terms of SEO.
Static Site Generation (SSG): It has worked more towards static websites and loads faster if it is enabled during the build time. It's on NextJS.
API Routes: You can set API routes right within the application; this does not complicate the idea of backend integration of NextJS.
File-Based Routing: NextJs works on file-based routing. This makes the structure and navigation of projects much easier.
NextJs can be a solution to all those applications which might require server-side rendering or static site generation. In addition, it is suitable for large applications in cases of routes with some complexity.
ReactJS vs NextJS: Major Differences
Although reactjs vs nextjs have so many advantages, the choice between them is still basically project-specific. Now, let's dive into the major differences of the nextjs vs reactjs debate:
1. Rendering Capabilities
ReactJS primarily depends on client-side rendering, which is perfect for SPAs but somehow faces issues with load time and SEO.
Since NextJS is integrated with SSR as well as SSG, it is very suitable for SEO-based sites and e-commerce applications.
2. Routing
In the case of ReactJS library, it does not include any built-in routing. You are going to be dependent upon another library for the routes creation as in the case of React Router.
With regards to NextJS, file-based routing is bundled in the package and therefore it provides you easier and simple handling and configuration of routes.
3. Learning Curve and Flexibility
ReactJS is much, much more flexible so you could turn it into anything you'd like. It's pretty difficult and a pain to work with if you don't know the best practices.
There is more convention set in place in NextJS, which means it's a bit less flexible but very straightforward in the learning path for beginners.
SEO and Performance
The general trend for ReactJS is that it is optimized to get fast performance on client-side rendering but lacks SEO.
It is all about SEO and performance since it supports options for SSR.
When to Use ReactJS
If it's about almost building a complex user interface where SEO matters less, then ReactJS would be the best. It's ideal for highly complex point-to-point interfaces, dashboards, etc., requiring efficient state management and user engagement.
ReactJS is much more flexible, and, in the final end, one of the go-to choices for the developers who wish to have an overall structure for their applications. Along with this, the community comprises a humongous amount of people who can provide a company for ReactJS Development or support.
When to Use NextJS
NextJS is suitable for projects where performance and SEO are at number one. Server-side rendering and static site generation make an ideal application that has good architecture for performance as well as proper SEO. E-commerce sites, content-driven websites, and high complex applications with client- and server-side logic may gain more with NextJS.
Moreover, if your team is a noob towards React, NextJS can benefit them in the development process as well. Considering all of these benefits of having full-stack possibilities nowadays, several NextJS Development Company specialize only in RectJS.
Which Framework Should You Choose: ReactJS or NextJS?
When to choose one of the following frameworks, ReactJS & NextJS- it solely depends upon the needs of your project:
If you are looking for the most flexibilities, and you would love to keep focus more on client-side rendering, but with complete ignorance towards SEO, then ReactJS would be a better option.
However, if you are going to pay most heed to SEO, you need better loading times, or you want to have a mix of server-side and client-side development, then NextJS will be at the top choice.
Summarizing it all, the nextjs vs reactjs choice is not exactly which one is better, but what best suits your goals. Both ReactJS Vs NextJS are strong tools and have their own share of strengths. In case it is for a single page application, static site, or web application that has SEO as well, you will surely find both ReactJS & NextJS fitting the bill.
Final Thoughts
ReactJS & NextJS has changed the face of web development wherein it has made things easier and faster to build high-performance applications with much ease. And whether you are considering to use either ReactJS & NextJS, never forget to remember the requirements of your project, familiarity of your team with the tools available and your scope. By getting the right framework, your application is sure to be built up to its potential, scalable and user-friendly.
Right ReactJS Development Company can make a difference between being adequately guided and fully equipped in that walk you have planned on taking on in the pursuit of development.
0 notes
yourteaminindia · 3 years ago
Text
Necessary Skills to Consider While Hiring React JS Developers
Tumblr media
With the popularity of ReactJs, companies and businesses expect a lot from developers. So, you must seek developers who have the necessary skills to adhere to the specific duties and responsibilities of the jobs. Here are a few skills you must look into before having a React Developer: 
Javascript and EcmaScript
ReactJs developers should know Js features, functions, and syntax. They should have experience in DOM, JavaScript Scopes, ES6, Event bubbling, and hoisting. A detailed understanding of the Ecma script is important to creating React applications. 
Technical Expertise
Developers should have a good technical understanding of JSON, Advanced HTML, Scsslint, ESLint, HTML, and Rest API. They must use the core components of React, like JSX, Component Lifecycle, hooks, class, functional components, etc. The experts should be familiar with Zoho, Jira, Jenkins, etc. 
Frameworks and Testing tools
React Js developers should be familiar with the unit testing frameworks and technologies like Sinon, Tape, Jest, Mocha, etc. They should have a good command of the frameworks and end-to-end testing tools like Cypress, CucumberJs, Selenium, NightwatchJs, puppeteer, and more. Moreover, a good knowledge of React frameworks and Libraries would be an added advantage. 
Multiple Technologies
Choose a developer who has a good command of multiple technologies and is compatible with the Mern Stack. They should also know about the Mern stack to deal with the issue of server loading time and JS application and manage several development requests. 
Version Control Systems
You must look for a professional React developer who is proficient in dealing with VCS like SVN, Firebase, TFS, Hit, Mercurial, etc. From them, Git is more popular for storing projects on the hosting platform, including GitHub, GitLab, BitBucket, etc.
Additionally, hiring developers should be skilled in the VCS to compare the old-new code and reduce possible errors and current. 
Js Build Tools
You must look for React Js front-end developers who are well-versed in various JS tools, React developer tools, and Redux DevTools. They should be experienced in maximizing the React Library and dealing with the new build tools like npm, Webpack, Yarn, and Visual Studio Code. 
React Basics and Styling Methods
Your professional developer should know about Creating React apps and their applications. They should be experts in technologies like Babel, JSX, NextJs, etc. 
Furthermore, they must know everything about CSS technologies like LESS, SASS, SCSS, and other pre-processors. Also, they should know technologies like CSS-in-JS and CSS frameworks like MaterialUI and Bootstrap) for styling React components. 
ReactJS Workflows 
ReactJS developers can easily manage projects and prioritize state management for their app performance optimization.
Moreover, they must know about popular libraries and structures of state management like Context API, React Native, Axios, React Router, Redux, MobX, etc. Their knowledge about new progress like React hooks can be an added benefit.
Sprint Planning
When hiring React developers, make sure that they are able to plan workflow and tasks to finish them on the said deadline. In other words, you must hire developers.
Workflows or tasks and finish them within the desired deadline. In short, you should hire React developers who are experts in sprint planning. They must be capable of dealing with task management tools to track and share the advancement of your project sprints.
Flexible Learning Curve
React features exceptional community support. It is one of the finest libraries for web development, which undergoes enormous changes and progresses every day. Therefore, the developers must be able to learn technology updates and changes when required.
Apart from these skills, you should consider interpersonal skills, such as acceptance of failure, efficient communication, teamwork, change management, creative thinking, and exposure to constructive feedback.
Read More: How to Hire the Best React Developers
0 notes
Text
When it comes to web development, things are always changing. New frameworks and libraries are constantly popping up, each trying to be the best. It can be tough to decide which one to use, especially when you have between NextJS vs ReactJS, top contenders.
Let’s take a closer look at the pros and cons of each technology to help you make the best choice for your website with Inwizards, Leading Software Development Company.
NextJS vs ReactJS: A Detailed Overview
A. NextJS: The All-in-One Powerhouse
Picture a powerful framework created specifically for ReactJS that simplifies development and provides a wide range of built-in features. This is where NextJS works its magic. It enables developers to build fast and efficient web applications with outstanding user experiences (UX).
Server-Side Rendering (SSR) and Static Site Generation (SSG): NextJS is great for improving website visibility on search engines and loading pages quickly. It can dynamically generate content on the server or create fast-loading static HTML files. This adaptability is beneficial for a wide range of projects.
Built-in Routing and Data Fetching: Gone are the days of piecing together routing and data fetching solutions. NextJS elegantly handles these critical aspects, allowing you to focus on building the core functionalities of your application.
Image Optimization: Images are often the silent culprits of slow websites. NextJS offers automatic image optimization, ensuring your visuals load efficiently without compromising quality.
Project Structure and Conventions: NextJS enhances code maintainability and streamlines development for teams by offering a definitive project structure and conventions.
Know Why Use ReactJS for Web Development? Read More
B. ReactJS: The Building Block Maestro
When comparing ReactJS and NextJS, it’s important to note that they serve different purposes. While NextJS is a full-fledged framework, ReactJS is a JavaScript library that is focused on creating user interfaces. Its component-based structure allows for great flexibility and versatility in development.
Components: Reusable Building Blocks: React applications are composed of reusable components, each representing a distinct portion of the UI. This modularity promotes code organisation, maintainability, and easier collaboration.
JSX (JavaScript XML): JSX is a syntax extension that allows you to write HTML-like structures directly within your JavaScript code. This makes for a more intuitive and efficient way to define components.
Virtual DOM: React’s virtual DOM plays a crucial role in optimising UI updates. It creates an in-memory representation of the UI, allowing React to efficiently identify changes and update only the necessary parts of the real DOM, resulting in smooth and performant UIs.
Looking for ReactJS Development Services? Consult Inwizards Software Technology
NextJS vs ReactJS Choosing the Right Tool
Now, let’s explore when each technology shines:
A. When to Embrace the Power of NextJS
SEO-Critical Websites and Landing Pages: The power of SSR and SSG makes NextJS an excellent choice for websites that need to rank highly in search engines. Initial content is readily available to search engine crawlers, boosting SEO.
Performance-Focused Applications: Whether it’s a dynamic e-commerce platform or a data-heavy dashboard, NextJS ‘s ability to optimize performance through SSR, SSG, and image optimization is a game-changer. Users will experience fast loading times and a seamless browsing experience.
Projects Requiring Built-in Functionalities: NextJS takes care of routing, data fetching, and other common development tasks, allowing you to focus on the core logic and business functionality of your application.
B. When ReactJS Takes the Stage
Complex, Single-Page Applications (SPAs): ReactJS excels in building interactive SPAs. Its flexible component-based architecture allows you to create intricate UIs that feel responsive and dynamic.
Fine-Grained Control over Project Structure: ReactJS doesn’t enforce a specific project structure. This flexibility gives you more control over how you organize your codebase, which can be beneficial for experienced developers or projects with unique requirements.
Existing Familiarity with Vanilla JavaScript or Other Front-End Libraries: If you or your team have a strong foundation in vanilla JavaScript or other front-end libraries like Angular, the transition to ReactJS might be smoother.
Confused Between ReactJS vs React Native? Check key Differences
Learning Curve and Community Support
Both NextJS and ReactJS boast vibrant communities, offering extensive resources and support for developers of all levels. However, there are some differences in the learning curve:
NextJS: Because NextJS builds upon ReactJS , having a solid understanding of React concepts is essential to effectively leverage NextJS’s features. If you’re new to both, expect a slightly steeper initial learning curve. However, the benefits of NextJS’s built-in functionalities and conventions can significantly reduce development time in the long run.
ReactJS: With its focus on core UI building blocks, ReactJS offers a more gradual learning curve. You can start with the fundamentals and progressively build your knowledge as your projects become more complex. However, for larger projects, managing the structure and integrating additional libraries for functionalities like routing or data fetching can require more effort.]
The online communities for both technologies are highly active and supportive. You’ll find a wealth of tutorials, documentation, forums, and Stack Overflow threads to answer your questions and guide your learning journey.
Want to Know Is it good to use Django and React together in 2024? Learn More
Conclusion: The Champion Lies in Your Project’s Needs
The battle between NextJS and ReactJS isn’t about which one is inherently “better.” It’s about identifying the champion that best suits your project’s specific requirements. Here’s a quick recap:
Choose NextJS if:
SEO and initial load times are paramount.
You need a high-performance web application.
You value built-in functionalities and a streamlined development experience.
Choose ReactJS if:
You’re building a complex, interactive SPA.
You need fine-grained control over project structure.
Your team has a strong foundation in vanilla JavaScript or other front-end libraries.
Ultimately, the best way to choose is to experiment with both technologies. Many developers find that NextJS is a fantastic choice for rapidly building modern web applications, while ReactJS offers the flexibility for highly customized and interactive UIs.
0 notes
bestmockup · 4 years ago
Text
React for Web Development
Choosing the best front-end technology nowadays is a big deal. Today’s web development era has witnessed quite a few technologies in the market, each designed to meet different needs. React is one such technology that has been utilized by almost each and every company. Ever since its launch, it has taken the front-end development space by storm.
EYMOCKUP
What is React?
React is a declarative and component-based JavaScript library to create user interfaces. It is the design layer for web applications. It is owned by Facebook and a community of companies and individual developers. It can be applied as a foundation while developing mobile or single-page applications, as it is optimal for obtaining swiftly modifying data that must be recorded.
Some features of React that make it suitable for Web Development It’s Easier to Learn for developers :
One of the main concerns developers have is choosing a framework (or library) that is easier to learn and implement. React is easy to grasp for developers who are familiar with JavaScript . So if you have a team of developers that are very well-versed with JavaScript, ReactJS should be your best bet. Speed : React basically allows developers to utilize individual parts of their application on both client-side and the server-side, which ultimately boosts the speed of the development process. In simple terms, different developers can write individual parts and all changes made won’t cause the logic of the application. It provides a unique Abstraction Layer : Another lesser-known business-related benefit with React is that it allows for a good abstraction layer, which means an end-user can’t access the complex internals. Your developer only needs to be aware of some basics, and they’d better off knowing the internal functionalities. Performance : React JS was designed to provide high performance in mind. The core of the framework offers a virtual DOM program and server-side rendering, which makes complex apps run extremely fast. Mobile app development : If you thought React is for web development only, you could not be more wrong! Facebook has already upgraded the framework for developing mobile native applications for both Android & iOS platforms. It is SEO-friendly : For any online business, search engine optimization is the gateway to success. Thanks to the fast rendering, React, compared to other frameworks, significantly reduces the page load time, which greatly helps businesses in securing the first rank on Google Search Engine Result Page.
99EFFECT
Conclusion
If you have a small project, inexperienced team and you don’t care how things are working as far as they are working, you should go for VueJs as it has the smallest bundle, easiest learning curve.
If you know from upfront that this project is going to be huge, you want your team to learn TypeScript and strict them to follow a particular set of libraries and project structure, you should go for Angular, as it has huge bundle size, mandatory TypeScript.
And finally, if you are not sure of projects scale but it might go big, you want your team to be good JavaScript developer than magically doing things, you want to keep experimenting with new technologies like GraphQL, you might need battle-tested server-side frameworks Gatsby and NextJs or you love declarative code which you can share cross-platform then you know what you have to choose.
0 notes
holytheoristtastemaker · 5 years ago
Link
 In this article, I will guide you step by step to set up Storybook with Next, Typescript, SCSS, and Jest.
Storybook is an open-source tool for developing UI components in isolation. It makes building stunning UIs organized and efficient. However, it can be quite tricky to set up with Nextjs.
Requirements
Node.js 10.13 or later
MacOS, Windows (including WSL), and Linux are supported
Create Nextjs App
Create a new Next.js app using create-next-app, which sets up everything automatically for you. To create a project, run this command:
$ npx create-next-app ✔ What is your project named? … my-app ✔ Pick a template › Default starter app
Enter your project name + hit return
You will be asked to choose a template: Use arrow key ⬇ to choose a Default starter app and hit return
After the installation is complete, to start the development server:
cd my-app yarn run dev
You should see this page on localhost:3000
Tumblr media
TypeScript
Next, let’s configure Typescript for our Next app
$ yarn add -D typescript @types/react @types/node
Create a tsconfig.json in the root folder — this is where you will put your typescript configurations.
/* root folder */ $ touch tsconfig.json
And add the following config to the file:
Remove index.js and create index.tsx file. You can do it manually or use these commands in the root folder
/* root folder */ rm -f pages/index.js touch pages/index.tsx
Add the following to index.tsx:
Restart your server and check out your http://localhost:3000/ by running:
$ yarn run dev
Tumblr media
Storybook
Next, we’ll configure Nextjs, SCSS, and Typescript for Storybook
$ yarn add -D @storybook/react @storybook/preset-typescript
Create .storybook folder and storybook config files:
/* root folder */ mkdir .storybook cd .storybook touch .storybook/main.js .storybook/next-preset.js .storybook/preview.js
Now we will go over how to configure these files.
next-preset.js
In this file, we will configure Typescript and SCSS to work with Storybook
$ yarn add -D sass style-loader css-loader sass-loader @babel/core babel-loader babel-preset-react-app
Add the following configuration to next-preset.js
SCSS
Create your style folder in the root and add global scss file.
/* root folder */ mkdir styles touch styles/global.scss
preview.js
In this file, we configure the “preview” iframe that renders your components. We will import your global scss file here.
main.js
main.js is the most important config file. This is where we place the main configuration of Storybook.
Create a story
Let’s create a simple Button component and a story to test our Storybook setup. First, create a components folder and 2 files Button.tsx and Button.stories.tsxin the folder.
/* root folder*/ mkdir components touch components/Button.tsx components/Button.stories.tsx
Then, add the following contents into 2 files:
Finally, add npm script to package.json to start storybook.
{ ... "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "storybook": "start-storybook -p 6006 -c .storybook" } }
Now, let’s run our Storybook.
$ yarn storybook
Tumblr media
You should see our global scss style took affect and 2 stories that we have created earlier to test the Button.
Tumblr media Tumblr media
Jest
Next, we will add unit tests and snapshot tests in Jest for testing components in Nextjs and Typescript.
First, let’s install these development dependencies for Jest.
$ yarn add -D jest @types/jest ts-jest babel-jest @types/enzyme enzyme enzyme-adapter-react-16
We’ll need to configure Enzyme to use the adapter, which we can do in Jest’s bootstrap file. Let’s create a config folder and place the setup file in there.
/* root folder */ mkdir config touch config/setup.js
This code will run also before each test but after the testing framework gets executed:
Now let’s create a config file for jest. If you place your setup file above at a different location then make sure to change your setupFiles: […] in jest.config.js.
/* root folder */ $ touch jest.config.js
Config babel.config.json
Lastly, we will add babel configurations. Let’s add these dev dependencies to our package.json by running the following command:
yarn add -D @babel/preset-env @babel/preset-react @babel/preset-flow @babel/plugin-transform-runtime babel-plugin-transform-es2015-modules-commonjs
In the root folder, create a babel config file. For some reasons, babel.rc does not work and I have to replace it with babel.config.json
/* root folder */ $ touch babel.config.json
Let’s create a test
Now, let’s run a simple unit test to test the index file that we created earlier to make sure that it has the welcome message “Welcome to My Next App!” as a “h1” element.
First, create a __test__ folder to keep our test files in one place and create index.test.tsx file.
/* root folder */ mkdir components/__test__ touch components/__test__/index.test.tsx
Snapshot testing
Finally, I will show you how to create a simple snapshot test. We use Snapshot testing to keep a copy of the structure of the UI component or a snapshot so when after we make any changes we can review the changes and update the snapshots. You can read more about Snapshot testing here.
To start, let’s install react-test-renderer, a library that enables you to render React components as JavaScript objects without the need for a DOM.
$ yarn add -D react-test-renderer
Now, create a file called Button.snapshot.test.tsx to test create new snapshots for the Button component.
$ touch components/__test__/Button.snapshot.test.tsx
Now, add the add npm script to package.json to run your tests
{ ... "scripts": { ... "test": "jest", "test:watch": "jest --watch", "test:coverage": "jest --coverage" } }
Go ahead and run your tests.
$ yarn run test
You should see 1 unit test and 1 snapshot test are passed
Tumblr media
If you run into errors such as “The default export is not a React Component in page: ‘/’” or “ReferenceError: regeneratorRuntime is not defined”, try to delete package-lock.json, node_modules folder, and .next folder and then restart your server, storybook and rerun your test again.
0 notes
mbaljeetsingh · 5 years ago
Text
Building a Blog with Next.js
In this article, we will use Next.js to build a static blog framework with the design and structure inspired by Jekyll. I’ve always been a big fan of how Jekyll makes it easier for beginners to setup a blog and at the same time also provides a great degree of control over every aspect of the blog for the advanced users.
With the introduction of Next.js in recent years, combined with the popularity of React, there is a new avenue to explore for static blogs. Next.js makes it super easy to build static websites based on the file system itself with little to no configuration required.
The directory structure of a typical bare-bones Jekyll blog looks like this:
. ├─── _posts/          ...blog posts in markdown ├─── _layouts/        ...layouts for different pages ├─── _includes/       ...re-usable components ├─── index.md         ...homepage └─── config.yml       ...blog config
The idea is to design our framework around this directory structure as much as possible so that it becomes easier to  migrate a blog from Jekyll by simply reusing the posts and configs defined in the blog.
For those unfamiliar with Jekyll, it is a static site generator that can transform your plain text into static websites and blogs. Refer the quick start guide to get up and running with Jekyll. This article also assumes that you have a basic knowledge of React. If not, React’s getting started page is a good place to start.
Installation
Next.js is powered by React and written in Node.js. So we need to install npm first, before adding next, react and react-dom to the project.
mkdir nextjs-blog && cd $_ npm init -y npm install next react react-dom --save
To run Next.js scripts on the command line, we have to add the next command to the scripts section of our package.json.
"scripts": {   "dev": "next" }
We can now run npm run dev on the command line for the first time. Let’s see what happens.
$ npm run dev > [email protected] dev /~user/nextjs-blog > next ready - started server on http://localhost:3000 Error: > Couldn't find a `pages` directory. Please create one under the project root
The compiler is complaining about a missing pages directory in the root of the project. We’ll learn about the concept of pages in the next section.
Concept of pages
Next.js is built around the concept of pages. Each page is a React component that can be of type .js or .jsx which is mapped to a route based on the filename. For example:
File                            Route ----                            ----- /pages/about.js                 /about /pages/projects/work1.js        /projects/work1 /pages/index.js                 /
Let’s create the pages directory in the root of the project and populate our first page, index.js, with a basic React component.
// pages/index.js export default function Blog() {   return <div>Welcome to the Next.js blog</div> }
Run npm run dev once again to start the server and navigate to http://localhost:3000 in the browser to view your blog for the first time.
Tumblr media
Out of the box, we get:
Hot reloading so we don’t have to refresh the browser for every code change.
Static generation of all pages inside the /pages/** directory.
Static file serving for assets living in the/public/** directory.
404 error page.
Navigate to a random path on localhost to see the 404 page in action. If you need a custom 404 page, the Next.js docs have great information.
Tumblr media
Dynamic pages
Pages with static routes are useful to build the homepage, about page, etc. However, to dynamically build all our posts, we will use the dynamic route capability of Next.js. For example:
File                        Route ----                        ----- /pages/posts/[slug].js      /posts/1                             /posts/abc                             /posts/hello-world
Any route, like /posts/1, /posts/abc, etc., will be matched by /posts/[slug].js and the slug parameter will be sent as a query parameter to the page. This is especially useful for our blog posts because we don’t want to create one file per post; instead we could dynamically pass the slug to render the corresponding post.
Anatomy of a blog
Now, since we understand the basic building blocks of Next.js, let’s define the anatomy of our blog.
. ├─ api │  └─ index.js             # fetch posts, load configs, parse .md files etc ├─ _includes │  ├─ footer.js            # footer component │  └─ header.js            # header component ├─ _layouts │  ├─ default.js           # default layout for static pages like index, about │  └─ post.js              # post layout inherts from the default layout ├─ pages │  ├─ index.js             # homepage |  └─ posts                # posts will be available on the route /posts/ |     └─ [slug].js       # dynamic page to build posts └─ _posts    ├─ welcome-to-nextjs.md    └─ style-guide-101.md
Blog API
A basic blog framework needs two API functions: 
A function to fetch the metadata of all the posts in _posts directory
A function to fetch a single post for a given slug with the complete HTML and metadata
Optionally, we would also like all the site’s configuration defined in config.yml to be available across all the components. So we need a function that will parse the YAML config into a native object.
Since, we would be dealing with a lot of non-JavaScript files, like Markdown (.md), YAML (.yml), etc, we’ll use the raw-loader library to load such files as strings to make it easier to process them. 
npm install raw-loader --save-dev
Next we need to tell Next.js to use raw-loader when we import .md and .yml file formats by creating a next.config.js file in the root of the project (more info on that).
module.exports = {   target: 'serverless',   webpack: function (config) {     config.module.rules.push({test:  /\.md$/, use: 'raw-loader'})     config.module.rules.push({test: /\.yml$/, use: 'raw-loader'})     return config   } }
Next.js 9.4 introduced aliases for relative imports which helps clean up the import statement spaghetti caused by relative paths. To use aliases, create a jsconfig.json file in the project’s root directory specifying the base path and all the module aliases needed for the project.
{   "compilerOptions": {     "baseUrl": "./",     "paths": {       "@includes/*": ["_includes/*"],       "@layouts/*": ["_layouts/*"],       "@posts/*": ["_posts/*"],       "@api": ["api/index"],     }   } }
For example, this allows us to import our layouts by just using:
import DefaultLayout from '@layouts/default'
Fetch all the posts
This function will read all the Markdown files in the _posts directory, parse the front matter defined at the beginning of the post using gray-matter and return the array of metadata for all the posts.
// api/index.js import matter from 'gray-matter' 
 export async function getAllPosts() {   const context = require.context('../_posts', false, /\.md$/)   const posts = []   for(const key of context.keys()){     const post = key.slice(2);     const content = await import(`../_posts/${post}`);     const meta = matter(content.default)     posts.push({       slug: post.replace('.md',''),       title: meta.data.title     })   }   return posts; }
A typical Markdown post looks like this:
--- title:  "Welcome to Next.js blog!" --- **Hello world**, this is my first Next.js blog post and it is written in Markdown. I hope you like it!
The section outlined by --- is called the front matter which holds the metadata of the post like, title, permalink, tags, etc. Here’s the output:
[   { slug: 'style-guide-101', title: 'Style Guide 101' },   { slug: 'welcome-to-nextjs', title: 'Welcome to Next.js blog!' } ]
Make sure you install the gray-matter library from npm first using the command npm install gray-matter --save-dev.
Fetch a single post
For a given slug, this function will locate the file in the _posts directory, parse the Markdown with the marked library and return the output HTML with metadata.
// api/index.js import matter from 'gray-matter' import marked from 'marked' 
 export async function getPostBySlug(slug) {   const fileContent = await import(`../_posts/${slug}.md`)   const meta = matter(fileContent.default)   const content = marked(meta.content)       return {     title: meta.data.title,      content: content   } }
Sample output:
{   title: 'Style Guide 101',   content: '<p>Incididunt cupidatat eiusmod ...</p>' }
Make sure you install the marked library from npm first using the command npm install marked --save-dev.
Config
In order to re-use the Jekyll config for our Next.js blog, we’ll parse the YAML file using the js-yaml library and export this config so that it can be used across components.
// config.yml title: "Next.js blog" description: "This blog is powered by Next.js" 
 // api/index.js import yaml from 'js-yaml' export async function getConfig() {   const config = await import(`../config.yml`)   return yaml.safeLoad(config.default) }
Make sure you install js-yaml from npm first using the command npm install js-yaml --save-dev.
Includes
Our _includes directory contains two basic React components, <Header> and <Footer>, which will be used in the different layout components defined in the _layouts directory.
// _includes/header.js export default function Header() {   return <header><p>Blog | Powered by Next.js</p></header> } 
 // _includes/footer.js export default function Footer() {   return <footer><p>©2020 | Footer</p></footer> }
Layouts
We have two layout components in the _layouts directory. One is the <DefaultLayout> which is the base layout on top of which every other layout component will be built.
// _layouts/default.js import Head from 'next/head' import Header from '@includes/header' import Footer from '@includes/footer' 
 export default function DefaultLayout(props) {   return (     <main>       <Head>         <title>{props.title}</title>         <meta name='description' content={props.description}/>       </Head>       <Header/>       {props.children}       <Footer/>     </main>   ) }
The second layout is the <PostLayout> component that will override the title defined in the <DefaultLayout> with the post title and render the HTML of the post. It also includes a link back to the homepage.
// _layouts/post.js import DefaultLayout from '@layouts/default' import Head from 'next/head' import Link from 'next/link' 
 export default function PostLayout(props) {   return (     <DefaultLayout>       <Head>         <title>{props.title}</title>       </Head>       <article>         <h1>{props.title}</h1>         <div dangerouslySetInnerHTML=/>         <div><Link href='/'><a>Home</a></Link></div>        </article>     </DefaultLayout>   ) }
next/head is a built-in component to append elements to the <head> of the page. next/link is a built-in component that handles client-side transitions between the routes defined in the pages directory.
Homepage
As part of the index page, aka homepage, we will list all the posts inside the _posts directory. The list will contain the post title and the permalink to the individual post page. The index page will use the <DefaultLayout> and we’ll import the config in the homepage to pass the title and description to the layout.
// pages/index.js import DefaultLayout from '@layouts/default' import Link from 'next/link' import { getConfig, getAllPosts } from '@api' 
 export default function Blog(props) {   return (     <DefaultLayout title={props.title} description={props.description}>       <p>List of posts:</p>       <ul>         {props.posts.map(function(post, idx) {           return (             <li key={idx}>               <Link href={'/posts/'+post.slug}>                 <a>{post.title}</a>               </Link>             </li>           )         })}       </ul>     </DefaultLayout>   ) }  
 export async function getStaticProps() {   const config = await getConfig()   const allPosts = await getAllPosts()   return {     props: {       posts: allPosts,       title: config.title,       description: config.description     }   } }
getStaticProps is called at the build time to pre-render pages by passing props to the default component of the page. We use this function to fetch the list of all posts at build time and render the posts archive on the homepage.
Tumblr media
Post page
This page will render the title and contents of the post for the slug supplied as part of the context. The post page will use the <PostLayout> component.
// pages/posts/[slug].js import PostLayout from '@layouts/post' import { getPostBySlug, getAllPosts } from "@api" 
 export default function Post(props) {   return <PostLayout title={props.title} content={props.content}/> } 
 export async function getStaticProps(context) {   return {     props: await getPostBySlug(context.params.slug)   } } 
 export async function getStaticPaths() {   let paths = await getAllPosts()   paths = paths.map(post => ({     params: { slug:post.slug }   }));   return {     paths: paths,     fallback: false   } }
If a page has dynamic routes, Next.js needs to know all the possible paths at build time. getStaticPaths supplies the list of paths that has to be rendered to HTML at build time. The fallback property ensures that if you visit a route that does not exist in the list of paths, it will return a 404 page.
Tumblr media
Production ready
Add the following commands for build and start in package.json, under the scripts section and then run npm run build followed by npm run start to build the static blog and start the production server.
// package.json "scripts": {   "dev": "next",   "build": "next build",   "start": "next start" }
The entire source code in this article is available on this GitHub repository. Feel free to clone it locally and play around with it. The repository also includes some basic placeholders to apply CSS to your blog.
Improvements
The blog, although functional, is perhaps too basic for most average cases. It would be nice to extend the framework or submit a patch to include some more features like:
Pagination
Syntax highlighting
Categories and Tags for posts
Styling
Overall, Next.js seems really very promising to build static websites, like a blog. Combined with its ability to export static HTML, we can built a truly standalone app without the need of a server!
The post Building a Blog with Next.js appeared first on CSS-Tricks.
via CSS-Tricks https://ift.tt/38RTO6t
0 notes
suzanneshannon · 5 years ago
Text
Building a Blog with Next.js
In this article, we will use Next.js to build a static blog framework with the design and structure inspired by Jekyll. I’ve always been a big fan of how Jekyll makes it easier for beginners to setup a blog and at the same time also provides a great degree of control over every aspect of the blog for the advanced users.
With the introduction of Next.js in recent years, combined with the popularity of React, there is a new avenue to explore for static blogs. Next.js makes it super easy to build static websites based on the file system itself with little to no configuration required.
The directory structure of a typical bare-bones Jekyll blog looks like this:
. ├─── _posts/          ...blog posts in markdown ├─── _layouts/        ...layouts for different pages ├─── _includes/       ...re-usable components ├─── index.md         ...homepage └─── config.yml       ...blog config
The idea is to design our framework around this directory structure as much as possible so that it becomes easier to  migrate a blog from Jekyll by simply reusing the posts and configs defined in the blog.
For those unfamiliar with Jekyll, it is a static site generator that can transform your plain text into static websites and blogs. Refer the quick start guide to get up and running with Jekyll. This article also assumes that you have a basic knowledge of React. If not, React’s getting started page is a good place to start.
Installation
Next.js is powered by React and written in Node.js. So we need to install npm first, before adding next, react and react-dom to the project.
mkdir nextjs-blog && cd $_ npm init -y npm install next react react-dom --save
To run Next.js scripts on the command line, we have to add the next command to the scripts section of our package.json.
"scripts": {   "dev": "next" }
We can now run npm run dev on the command line for the first time. Let’s see what happens.
$ npm run dev > [email protected] dev /~user/nextjs-blog > next ready - started server on http://localhost:3000 Error: > Couldn't find a `pages` directory. Please create one under the project root
The compiler is complaining about a missing pages directory in the root of the project. We’ll learn about the concept of pages in the next section.
Concept of pages
Next.js is built around the concept of pages. Each page is a React component that can be of type .js or .jsx which is mapped to a route based on the filename. For example:
File                            Route ----                            ----- /pages/about.js                 /about /pages/projects/work1.js        /projects/work1 /pages/index.js                 /
Let’s create the pages directory in the root of the project and populate our first page, index.js, with a basic React component.
// pages/index.js export default function Blog() {   return <div>Welcome to the Next.js blog</div> }
Run npm run dev once again to start the server and navigate to http://localhost:3000 in the browser to view your blog for the first time.
Tumblr media
Out of the box, we get:
Hot reloading so we don’t have to refresh the browser for every code change.
Static generation of all pages inside the /pages/** directory.
Static file serving for assets living in the/public/** directory.
404 error page.
Navigate to a random path on localhost to see the 404 page in action. If you need a custom 404 page, the Next.js docs have great information.
Tumblr media
Dynamic pages
Pages with static routes are useful to build the homepage, about page, etc. However, to dynamically build all our posts, we will use the dynamic route capability of Next.js. For example:
File                        Route ----                        ----- /pages/posts/[slug].js      /posts/1                             /posts/abc                             /posts/hello-world
Any route, like /posts/1, /posts/abc, etc., will be matched by /posts/[slug].js and the slug parameter will be sent as a query parameter to the page. This is especially useful for our blog posts because we don’t want to create one file per post; instead we could dynamically pass the slug to render the corresponding post.
Anatomy of a blog
Now, since we understand the basic building blocks of Next.js, let’s define the anatomy of our blog.
. ├─ api │  └─ index.js             # fetch posts, load configs, parse .md files etc ├─ _includes │  ├─ footer.js            # footer component │  └─ header.js            # header component ├─ _layouts │  ├─ default.js           # default layout for static pages like index, about │  └─ post.js              # post layout inherts from the default layout ├─ pages │  ├─ index.js             # homepage |  └─ posts                # posts will be available on the route /posts/ |     └─ [slug].js       # dynamic page to build posts └─ _posts    ├─ welcome-to-nextjs.md    └─ style-guide-101.md
Blog API
A basic blog framework needs two API functions: 
A function to fetch the metadata of all the posts in _posts directory
A function to fetch a single post for a given slug with the complete HTML and metadata
Optionally, we would also like all the site’s configuration defined in config.yml to be available across all the components. So we need a function that will parse the YAML config into a native object.
Since, we would be dealing with a lot of non-JavaScript files, like Markdown (.md), YAML (.yml), etc, we’ll use the raw-loader library to load such files as strings to make it easier to process them. 
npm install raw-loader --save-dev
Next we need to tell Next.js to use raw-loader when we import .md and .yml file formats by creating a next.config.js file in the root of the project (more info on that).
module.exports = {   target: 'serverless',   webpack: function (config) {     config.module.rules.push({test:  /\.md$/, use: 'raw-loader'})     config.module.rules.push({test: /\.yml$/, use: 'raw-loader'})     return config   } }
Next.js 9.4 introduced aliases for relative imports which helps clean up the import statement spaghetti caused by relative paths. To use aliases, create a jsconfig.json file in the project’s root directory specifying the base path and all the module aliases needed for the project.
{   "compilerOptions": {     "baseUrl": "./",     "paths": {       "@includes/*": ["_includes/*"],       "@layouts/*": ["_layouts/*"],       "@posts/*": ["_posts/*"],       "@api": ["api/index"],     }   } }
For example, this allows us to import our layouts by just using:
import DefaultLayout from '@layouts/default'
Fetch all the posts
This function will read all the Markdown files in the _posts directory, parse the front matter defined at the beginning of the post using gray-matter and return the array of metadata for all the posts.
// api/index.js import matter from 'gray-matter' 
 export async function getAllPosts() {   const context = require.context('../_posts', false, /\.md$/)   const posts = []   for(const key of context.keys()){     const post = key.slice(2);     const content = await import(`../_posts/${post}`);     const meta = matter(content.default)     posts.push({       slug: post.replace('.md',''),       title: meta.data.title     })   }   return posts; }
A typical Markdown post looks like this:
--- title:  "Welcome to Next.js blog!" --- **Hello world**, this is my first Next.js blog post and it is written in Markdown. I hope you like it!
The section outlined by --- is called the front matter which holds the metadata of the post like, title, permalink, tags, etc. Here’s the output:
[   { slug: 'style-guide-101', title: 'Style Guide 101' },   { slug: 'welcome-to-nextjs', title: 'Welcome to Next.js blog!' } ]
Make sure you install the gray-matter library from npm first using the command npm install gray-matter --save-dev.
Fetch a single post
For a given slug, this function will locate the file in the _posts directory, parse the Markdown with the marked library and return the output HTML with metadata.
// api/index.js import matter from 'gray-matter' import marked from 'marked' 
 export async function getPostBySlug(slug) {   const fileContent = await import(`../_posts/${slug}.md`)   const meta = matter(fileContent.default)   const content = marked(meta.content)       return {     title: meta.data.title,      content: content   } }
Sample output:
{   title: 'Style Guide 101',   content: '<p>Incididunt cupidatat eiusmod ...</p>' }
Make sure you install the marked library from npm first using the command npm install marked --save-dev.
Config
In order to re-use the Jekyll config for our Next.js blog, we’ll parse the YAML file using the js-yaml library and export this config so that it can be used across components.
// config.yml title: "Next.js blog" description: "This blog is powered by Next.js" 
 // api/index.js import yaml from 'js-yaml' export async function getConfig() {   const config = await import(`../config.yml`)   return yaml.safeLoad(config.default) }
Make sure you install js-yaml from npm first using the command npm install js-yaml --save-dev.
Includes
Our _includes directory contains two basic React components, <Header> and <Footer>, which will be used in the different layout components defined in the _layouts directory.
// _includes/header.js export default function Header() {   return <header><p>Blog | Powered by Next.js</p></header> } 
 // _includes/footer.js export default function Footer() {   return <footer><p>©2020 | Footer</p></footer> }
Layouts
We have two layout components in the _layouts directory. One is the <DefaultLayout> which is the base layout on top of which every other layout component will be built.
// _layouts/default.js import Head from 'next/head' import Header from '@includes/header' import Footer from '@includes/footer' 
 export default function DefaultLayout(props) {   return (     <main>       <Head>         <title>{props.title}</title>         <meta name='description' content={props.description}/>       </Head>       <Header/>       {props.children}       <Footer/>     </main>   ) }
The second layout is the <PostLayout> component that will override the title defined in the <DefaultLayout> with the post title and render the HTML of the post. It also includes a link back to the homepage.
// _layouts/post.js import DefaultLayout from '@layouts/default' import Head from 'next/head' import Link from 'next/link' 
 export default function PostLayout(props) {   return (     <DefaultLayout>       <Head>         <title>{props.title}</title>       </Head>       <article>         <h1>{props.title}</h1>         <div dangerouslySetInnerHTML=/>         <div><Link href='/'><a>Home</a></Link></div>        </article>     </DefaultLayout>   ) }
next/head is a built-in component to append elements to the <head> of the page. next/link is a built-in component that handles client-side transitions between the routes defined in the pages directory.
Homepage
As part of the index page, aka homepage, we will list all the posts inside the _posts directory. The list will contain the post title and the permalink to the individual post page. The index page will use the <DefaultLayout> and we’ll import the config in the homepage to pass the title and description to the layout.
// pages/index.js import DefaultLayout from '@layouts/default' import Link from 'next/link' import { getConfig, getAllPosts } from '@api' 
 export default function Blog(props) {   return (     <DefaultLayout title={props.title} description={props.description}>       <p>List of posts:</p>       <ul>         {props.posts.map(function(post, idx) {           return (             <li key={idx}>               <Link href={'/posts/'+post.slug}>                 <a>{post.title}</a>               </Link>             </li>           )         })}       </ul>     </DefaultLayout>   ) }  
 export async function getStaticProps() {   const config = await getConfig()   const allPosts = await getAllPosts()   return {     props: {       posts: allPosts,       title: config.title,       description: config.description     }   } }
getStaticProps is called at the build time to pre-render pages by passing props to the default component of the page. We use this function to fetch the list of all posts at build time and render the posts archive on the homepage.
Tumblr media
Post page
This page will render the title and contents of the post for the slug supplied as part of the context. The post page will use the <PostLayout> component.
// pages/posts/[slug].js import PostLayout from '@layouts/post' import { getPostBySlug, getAllPosts } from "@api" 
 export default function Post(props) {   return <PostLayout title={props.title} content={props.content}/> } 
 export async function getStaticProps(context) {   return {     props: await getPostBySlug(context.params.slug)   } } 
 export async function getStaticPaths() {   let paths = await getAllPosts()   paths = paths.map(post => ({     params: { slug:post.slug }   }));   return {     paths: paths,     fallback: false   } }
If a page has dynamic routes, Next.js needs to know all the possible paths at build time. getStaticPaths supplies the list of paths that has to be rendered to HTML at build time. The fallback property ensures that if you visit a route that does not exist in the list of paths, it will return a 404 page.
Tumblr media
Production ready
Add the following commands for build and start in package.json, under the scripts section and then run npm run build followed by npm run start to build the static blog and start the production server.
// package.json "scripts": {   "dev": "next",   "build": "next build",   "start": "next start" }
The entire source code in this article is available on this GitHub repository. Feel free to clone it locally and play around with it. The repository also includes some basic placeholders to apply CSS to your blog.
Improvements
The blog, although functional, is perhaps too basic for most average cases. It would be nice to extend the framework or submit a patch to include some more features like:
Pagination
Syntax highlighting
Categories and Tags for posts
Styling
Overall, Next.js seems really very promising to build static websites, like a blog. Combined with its ability to export static HTML, we can built a truly standalone app without the need of a server!
The post Building a Blog with Next.js appeared first on CSS-Tricks.
You can support CSS-Tricks by being an MVP Supporter.
Building a Blog with Next.js published first on https://deskbysnafu.tumblr.com/
0 notes
laurelkrugerr · 5 years ago
Text
Smashing Podcast Episode 23 With Guillermo Rauch: What Is Next.js?
We’re talking about Next.js. What is it, and where might it fit into our web development workflow? Drew McLellan talks to co-creator Guillermo Rauch to find out.
Today, We’re talking about Next.js. What is it, and where might it fit into our web development workflow? I spoke to co-creator Guillermo Rauch to find out.
Show Notes
Weekly Update
Transcript
Drew McLellan: He’s the founder and CEO of Vercel, a cloud platform for static sites that fits around a Jamstack workflow. He’s also the co-creator of Next.js. He previously founded LearnBoost and CloudUp, and is well-known as the creator of several popular node open source libraries like Socket.io, Mongoose, and SlackIn. Prior to that, he was a core developer on MooTools, so we know he knows his way around JavaScript like the back of his hand. Did you know he once received a royal commission from the King of Spain to create an ice sculpture out of iceberg lettuce? My smashing friends, please welcome Guillermo Rauch. Hi Guillermo, how are you?
Guillermo Rauch: I’m smashing freaking good, thanks for having me.
Drew: I wanted to talk to you today about the whole world of Next.js, as it’s something that obviously you’re personally very knowledgeable about, having been involved as a co-creator right from the start. Next.js is one of those project names that has been on my radar while working in the Jamstack space, but it isn’t something that I’ve actually personally looked at or worked with too closely before. For people who are like me, who perhaps aren’t aware of what Next.js is, perhaps you could give us a bit of background into what it is and what problems it tries to solve.
Guillermo: Next.js is a very interesting member of the Jamstack universe, because Next.js actually started being a fully SSR-focused framework. It started getting a lot of adoption outside the Jamstack space where people were building very large things specifically when they wanted to have user generated content or dynamic content or social networks or e-commerce, and they knew that they wanted SSR because their data set was very large or very dynamic. It fell under the radar I think for a lot of people in the Jamstack world, but later on Next.js gained the capabilities for static optimization.
Guillermo: On one hand, for example, if you wouldn’t do data fetching at the top level of your page with Next.js, your React page would be … Also by the way, for those who are not fully in the know, Next.js is simply React framework for production, but has this capability of doing some rendering. Then when you get in static optimization capabilities, if you wouldn’t define data fetching at the top level of your page, it automatically exported as HTML instead of trying to do anything with server rendering.
Guillermo: Then later on, it also gained the capability for static site generation, meaning that you can define a special data hook, but that data hook gets data at build time. Next.js became a hybrid, very powerful dynamic and static framework, and now it’s been growing a lot in the Jamstack space as well.
Drew: People might say that React is already a framework, you certainly hear it described that way. What does it actually mean to be a framework for React?
Guillermo: That’s a great observation, because I always point out to people that React at Facebook and React outside of Facebook are completely different beasts. React at Facebook actually is used together with server rendering, but even their server rendering, for example, doesn’t use Node.js, it uses a highly specialized virtual machine called Hermes which communicates to their sort of production hack and PHP stack and answers all this advanced and exotic Facebook needs.
Guillermo: When they open source React, it’s almost like open sourcing a component. I always call it like open sourcing the engine, but not giving you the car. What happened is people really wanted to go and drive with it, they wanted to get to places with React. In the community, people started creating cars, and they would embed React as the engine, which was what the driver, the developer was after in the first place, make React the fundamental part of the car. Things like Next.js and Gatsby and React Static and many other frameworks started appearing that were solving the need for like, “I actually want to create fully loaded pages and applications.”
Guillermo: Whereas React was kind of more like the component and the engine for specific widgets within the page, this was certainly the case for Facebook. They will broadly and publicly admit that they invented it for things like the notification batch, the chat widget, the newsfeed component, and those components were React routes that were embedded into the contents of the production existing app with lots and lots of lines of code and even other JS libraries and frameworks.
Guillermo: What it means to create a framework for React, it means you make React the fundamental part of the story, hopefully and this is something we’ll try to do with Next.js, the learning curve is primarily about React with some added surface for Next.js, particularly around data fetching and routing. We also do a lot of production optimizations, so when you get React, when you get Create React app, which is sort of like, I like to call it a bootstrapped car that Facebook gives you, maybe the needs for production are not really met. Or if you try to do it yourself by configuring Webpack and configuring Babel and configuring server rendering and static generation, it’s also hard to put together a car from scratch. Next.js will give you this zero config and also production optimized set of defaults around building entire big things with React.
Drew: So it’s like it almost puts a sort of ecosystem around your React app with a collection of pre-configured tools to enable you to-
Guillermo: Correct.
Drew: Hit the ground running and do static site generation or server rendering or routing.
Guillermo: Correct, and you used a word there that is very, very key to all this, which is pre-configured. We’re fortunate enough to draw the attention of Google Chrome as a contributor to Next.js. One of the leaders of this project, her thing is that when they were working on frameworks internally at Google, they faced a lot of the same problems that the community and open source are facing today. There were many different competing initiatives at Google on how to scale and make really performant web apps out of the box.
Guillermo: You would join as a Googler and you would be given a framework with which you would create really big production ready, very high performance applications. Shubie was part of a lot of those initiatives, and what she found is that there’s two key ingredients to making a framework succeed at scale. One is pre-configuration, meaning that you come to work, you’re going to start a brand new app, you should be given something that is already ready to go and meets a lot of the production demands that are known at that given point in time.
Guillermo: On the other hand, the other really important step that we’re working towards is conformance. You can be given the most highly optimized production ready pre-configured framework, but if you go ahead and, for example, start introducing lots of heavy dependencies or third party scripts or use very inefficient layouts that take a long time to paint and so on and so forth, then you’re going to make that pre-configuration sort of go to waste. By mixing pre-configuration with conformance over time, the developer is not only having a great starting point, but it’s also guided to success over time.
Drew: It seems that a characteristic of Next.js, that it’s quite opinionated, the UI layer is React, it uses type script, uses Webpack, and those are all choices that the project has made and that’s what you get. Correct me if I’m wrong, but you couldn’t swap out React for Vue, for example, within Next.js.
Guillermo: That’s a good point, where technical decision making meets sort of an art. On one hand, I’d really like to claim that Next is very unopinionated, and the reason for this is that if you specifically go to github.com/vercel/nextjs and the examples directory, you’ll see that there’s almost like a combinatoric explosion of technologies that you can use together with Next.js. You’ll see fire-based, you’ll see Graphic UL, you’ll see Apollo, you’ll see RedUX, you’ll see MobX, in the CSS space there’s even more options.
Guillermo: We have a default CSS port that’s embedded, but then you can use two flavors of it, one with import, one with style tags which we call Style JSX, which resembles very much like the web platform approach to Shadow CSS. The reason I mean unopinionated is we want Next.js to stay very close to the “bare metal” of the web, and not introduce lots of primitives that if the web from 10 years from today would be incompatible with. Then if you look at the examples, you’ll see that there’s all these other technologies that you can plug in.
Guillermo: The base level of opinionation is that there is React and you’re not going to be able to replace it, at least anytime soon. Then there is the concept of you should be able to create pages, and this was kind of like a new thing when we first launched it, which was everyone is trying to create single-page applications. What we realized is like the internet is made up of websites with lots of pages that create distinct entry points via search engines, via Twitter, via Facebook, via social networks, via email companions, like you always guide the person toward an entry point, and that person that comes through that entry point shouldn’t have to download the burden of the entirety of the application.
Guillermo: Then that path led us to implementing server rendering, then static generation for multiple pages, et cetera, et cetera. That other base level of opinionation is Next should be a framework that works for the web, not against the web. Then on top of that, React was missing data fetching and routing primitives, and we added those. There’s a level of opinionation that has to deal with like everybody needs a router, so might as well have a router built in by default.
Drew: The big advantage of having those defaults is it takes away a lot of the complexity of choice, that it’s just there, it’s configured, and you can just start using it without needing to think too much, because I think we’ve all-
Guillermo: Exactly.
Drew: Been in situations where there are far too many choices of what components to use, and it can be overwhelming and get in the way of being productive.
Guillermo: Exactly.
Drew: What sort of projects do you see people using Next.js for? Is it for basically any situation where you might build a production React app, or is it more suited to particular types of content heavy sites? Does it matter in that sense?
Guillermo: Yeah, so this has been an age old debate of the web, is the web for apps, is the web for sites, is it a hybrid? What is the role of JavaScript, et cetera, et cetera? It’s kind of hard to give a straight up answer, but my take on this is the web was evolved always to be a hybrid of content that is evolving to be more and more dynamic and personal to the user. Even when you say like a content website, the high end content websites of the world have code bases that are very much comparable to apps.
Guillermo: A great example here is like New York Times, they’ll give you embedded widgets with data analysis tools and interactive animation, and they’ll recommend what story to read next, and they have a subscription model built in which sometimes gives you part of the content and sometimes counts how many articles you’ve read. Like if I told you this when the web was invented, like Tim Berners-Lee would be like, “No, that’s crazy, that’s not possible on the web,” but that’s the web we have today.
Guillermo: Next.js is answering a lot of these complex modern needs, which means you’ll see lots of e-commerce usage, you’ll see lots of content with that. E-commerce meaning, by the way, not just like buy items, but experiences like the largest real estate websites on the web, realtor.com, zillow.com, trulio.com, that entire category is all Next.js, then content sites. We just onboarded washingtonpost.com as a customer of Vercel and Next.js, we have then a third category that is more emergent but very interesting, which is full apps and user-generated content, like tiktok.com, and kind of like you would think the original single-page application use case as well being quite represented there.
Guillermo: Next.js sort of shines when you need to have lots of content that has to be served very, very quickly, has to be SEO Company optimized, and at the end of the day, it’s a mix of dynamic and static.
Drew: I’ve previously spoken to Marcy Sutton about Gatsby, which seems to be in a similar sort of space. It’s always great to see more than one solution to a problem and having choice for one project to the next. Would you say that Next.js and Gatsby are operating in the same sort of problem space, and how similar or dissimilar are they?
Guillermo: I think there’s an overlap for some use cases. For example, my personal blog rauchg.com runs on Next.js, it could’ve just been a great Gatsby blog as well. There is that overlap in the smaller static website sort of space, and by small I don’t mean not relevant. A lot of dotcoms that are super, super important run on basically static web, so that’s the beauty of Jamstack in my opinion. Because Next.js can statically optimize your pages and then you can get great Lighthouse scores through that, you can use it for overlapping use cases.
Guillermo: I think the line gets drawn when you start going into more dynamic needs and you have lots of pages, you have the need to update them at one time. Although Gatsby is creating solutions for those, Next.js already has production ready live solutions that work with any sort of database, any sort of data backend for basically “generating” or “printing” lots and lots of pages. That’s where today customers are going to Next.js instead of Gatsby.
Drew: One of the problems that everyone seems to run into as their JavaScript-based solution gets bigger is performance and how things can start getting pretty slow, you have big bundle sizes. Traditionally, things like code splitting can be fairly complex to get configured correctly. I see that’s one of the features that jumped out at me of Next.js, that it claims that the code splitting is automatic. What does Next.js do in terms of code splitting to make that work?
Guillermo: Your observation is 100% right. One of the biggest things with the web and one of the biggest weights on the web is JavaScript, and just like different materials have different densities and weights irrespective of the actual physical volume, JavaScript tends to be a very dense, heavy element. Even small amounts of JavaScript compared to, like for example, images that can be processed asynchronously and off the main thread, JavaScript tends to be particularly bothersome.
Guillermo: Next.js has invested a tremendous amount of effort into automatically optimizing your bundles. The first one that was my first intuition when I first came up with the idea for Next.js was you’re going to define, for example, 10 routes. In the Next.js world you create a pages directory and you drop your files in there Index.js, About.js, Settings.js, Dashboard.js, Termsofservice.js, Signup.js, Login.js. Those become entry points to your application that you can share through all kinds of media.
Guillermo: When you enter those, we want to give you JS that is relevant for that page first and foremost, and then perhaps a common bundle so that subsequent navigations within the system are very snappy. Next.js also, which is very, very nice, automatically pre-fetches the rest of the pages that are connected to that entry point, such that it feels like a single-page application. A lot of people say like, “Why not just use Create React app if I know that I have maybe a couple routes?” I always tell them, “Look, you can find those as pages, and because Next.js will automatically pre-fetch ones that are connected, you end up getting your single-page application, but it’s better optimized with regards to that initial paint, that initial entry point.”
Guillermo: That was the initial code splitting approach, but then it became a lot more sophisticated over time. Google contributed a very nice optimization called Module and No Module, which will give differential JS to modern browsers, and legacy JS that’s heavy with polyfields to other browsers, and this optimization 100% automated and produces massive savings. We gave it to one of our customers that we host on Vercel called Parnaby’s, I believe if I’m not mistaken, it was something very, very significant. It was maybe like 30% savings in code sizes, and that was just because they upgraded Next.js to a version that optimized JS bundles better.
Guillermo: That was kind of the point that we were going over earlier, which is you choose Next.js and it only gets better and more optimal over time, it’ll continue to optimize things on your behalf. Those are, again, pre-configurations that you would never have to deal with or be bothered with, and the research of which you don’t ever even want to do, to be honest. Like I wasn’t obviously very involved with this, but I look at some of the internal discussions and they were discussing all these polyfields that only mattered to Internet Explorer X and Soho, I was like, “I don’t even want to know, let’s just upgrade Next.js and get all these benefits.”
Drew: There is sometimes great benefits on there with sticking with the defaults and sticking with the most common configuration of things, which seems to be really the Next.js approach. I remember when I started writing PHP back in the early 2000s, and everybody was using PHP and MySQL, and at the time I’d just come from Windows so I wanted to use PHP and Microsoft Sequel Server. You can do it, but you’re swimming against the tide the whole way. Then as soon as I just switched over to MySQL, the whole ecosystem just started working for me and I didn’t need to think about it.
Guillermo: Yeah, everything just clicks, that is such a great observation. We see that all the time, like the Babel ecosystem is so powerful now that you could become, for example, a little bit faster by swapping Babel for something else, but then you trade off that incredible ecosystem compatibility. This is something you touched on performance earlier, and like for a lot of people, build performance and static generation performance is a big bottleneck, and this is something that we are very diligent in improving the performance of our tools incrementally.
Guillermo: For example, one of the things that Next.js is doing now is that it’s upgrading its default from Webpack 4 to Webpack 5, which has some breaking things, and that’s why we’re first offering it to people as an opt-in flag, but later on it’ll become the default. Webpack 5 makes incredible performance improvements, but we’re not sacrificing the Webpack ecosystem, we incrementally improved. Sure, there were some very small things that needed to be sacrificed, but that’s an incredible benefit of the JS ecosystem today that a lot of people are glossing over, I think, because maybe they see, “Oh, we could’ve done X in Soho, maybe it was a little faster, or maybe MPM in Soho would take less time.” They pick up some details and they miss the bigger picture, which is the ecosystem value is enormous.
Drew: The value of having all the configuration and the maintenance and that side of it done by a project like Next.js rather than taking that on yourself by swapping to using something else is incredible, because as soon as you move away from those defaults, you’re taking on the burden of keeping all the compatibilities going and doing it yourself. One of the things that I’ve been really interested in with Next.js is there are options available for either doing static site generation or server-side rendering, or maybe a hybrid of the two perhaps. I think there’s been some recent changes to this in a recent update, can you tell us a little bit about that and when you might choose one or the other?
Guillermo: Yeah, for sure. One of the key components of this hybrid approach combined with the page system that I described earlier is that you can have pages that are fully static or pages that server rendered. A page that’s fully static has the incredible benefit of what I call static hoisting, which is you can take that asset and automatically put it at the edge. By putting it at the edge, I mean you can cache it, you can preemptively cache it, you can replicate it, you can make it so that when a request comes in, it never touches the server because we know ahead of time, “Hey, Slash Index is a static.”
Guillermo: That’s a very, very interesting benefit when it comes down to serving global audiences. You basically get an automatic CDN out of the box, especially when you deploy the modern edge networks like Vercel or AWS Amplify or Netlify and so on. Next.js has this premise of if it can be made static, it should be static. When you’re first starting a project and you’re working on your first page or you’re kicking the tires of the framework, might as well make everything static.
Guillermo: Even for high end needs, so for example, vercel.com, our own usage of Next.js is fully static. It’s a combination of fully static and static site generation, so all our marketing agency pages are static, our blog is statically generated from a dynamic data source, and then our dashboard which has lots of dynamic data, but we can deliver it as shells or skeletons, all the pages associated with viewing your deployments, viewing your projects, viewing your logs, et cetera, et cetera, are all basically static pages with client-side JavaScript.
Guillermo: That serves us incredibly well because everything where we need a very fast first-pane performance is already pre-rendered, everything that needs SEO Company, already pre-rendered, and everything that’s extremely dynamic, we only have to worry about security, for example, from the perspective of the client side which uses the same API calls that, for example, our CLI used or our integrations use, et cetera, et cetera. A fully static website, very cheap to operate, incredibly scalable and so on and so forth.
Guillermo: Now, one particular thing that we needed with our blog was we wanted to update the data very quickly. We wanted to fix a typo very quickly and not wait for an entire build to happen, and this is a very significant benefit of Next.js, that as you straddle from a static to a dynamic, it gives you these in between solutions as well. For our blog we used incremental static generation, so essentially we can rebuild one page at a time when the underlying content changes.
Guillermo: Imagine that we had not just a couple hundred blog posts and we had lots of blog posts being generated all the time and being updated all the time, like I mentioned one of our customers, Washington Post, in that case you need to go more toward full SSR, especially as you start customizing the content for each user. That journey of complexity that I just described started from I have one marketing agency page, to I have a blog that has a couple thousand pages, to I have tens of thousands or millions of pages. That’s the Next.js journey that you can traverse with your own business.
Guillermo: Then you start as a developer to choose between perhaps less responsibility to more responsibility, because when you opt in to using SSR, you’re now executing code on the server, you’re executing code on the cloud, there’s more responsibility with more power. The fact that you can decide where you use each kind of tool is I think a very, very interesting benefit of Next.
Drew: Just in practicalities of combining the static site generation and the server-side rendering, how does that work in terms of the server element? Are you needing a dedicated platform like Vercel to be able to achieve that, or is that something that can be done more straightforwardly and more simply?
Guillermo: Next.js gives you a dev server, so you download Next and you run your Next Dev, and that’s the dev server. The dev server is obviously incredibly optimized for development, like it has the latest fast refresh technology that Facebook released, where … Actually, Facebook didn’t release it, Facebook uses it internally to get the best and most performant and most reliable hot module replacement, such that you’re basically typing and it changes are reflecting on the screen, so that’s the dev server.
Guillermo: Then Next gives you a production server called Next Start, and Next Start has all the capabilities of the framework for self-hosting. The interesting thing about Vercel is that when you deploy Next to it, it gets automatically optimized and it’s 100% serverless, meaning there’s no responsibility whatsoever of administration, scaling, cashing and cashing validation, purging, replication, global fail over and so on and so forth that you would have to take on when you run Next Start yourself.
Guillermo: That’s also the great benefit of Next.js, so for example, apple.com has several different properties, subdomains and pages on dotcom on Next.js they self-host, due to very, very advanced and stringent security and privacy needs. On the other hand, washingtonpost.com uses Vercel, so we have this sort of wide range of users, and we’re extremely happy to support all of them. The nice thing about where serverless is headed in my opinion is it can give you best of both worlds in terms of the most optimal performance that only gets better over time, with the best developer experience of like, “Hey, I don’t have to worry about any sort of infrastructure.”
Drew: The Next.js is an open source project that’s being developed by the team at Vercel. Are there other contributors outside of Vercel?
Guillermo: Yeah, so Google Chrome being the main one that actively submit server PRs, help us with optimizations and testing it with partners, like very large Next.js users that are already part of the Google ecosystem, for example, due to using lots and lots of apps, so they need to be involved closely as partners. Facebook, we maintain a great relationship with the Facebook team. For example, fast refresh, we were the first React framework to land that, and they helped guide us through all the things that they learned of using React and fast refresh at Facebook.
Guillermo: We work with lots of partners that have very large deployments of Next.js apps in the wild from all kinds of different sort of use cases, like imagine e-commerce and content. Then there’s just lots and lots of independent contributors, people that use Next.js personally, but also educators and members of front infrastructure teams at large companies. It’s a very, very wide community effort.
Drew: It sounds like the concern that somebody might have, that this is being developed in a significant part by Vercel, that they might have the concern that they’re going to get sort of locked into deploying on that particular platform, but it sounds very much like that’s not the case at all, and they could develop a site and deploy it on Firebase or Netlify or…
Guillermo: Yeah, absolutely. I like to compare it a lot for like the Kubernetes of the Front End age in a way, because at the end of the day I am a firm believer that … Kubernetes is something that pretty much almost everyone needs when they need to run LinUX processes, like you were talking about opinionation and you’re saying it’s a good technology, it’s very much not opinionated, but there is some opinionation that we kind of forget about. It’s like at the end of the day, it grew out of running a specific demons of LinUX programs packaged as containers.
Guillermo: Next is in a similar position, because what we take for being the universal primitive of the world as a React component, obviously it’s opinionated, but we do think that for lots of enterprises, just like they all gravitate towards LinUX, we are seeing the same thing towards React and Vue, but Vue luckily has NUXt too, which is a very awesome solution, it’s equivalent in ideation and principles as Next. We’re gravitating towards these platforms like Next.js, like NUXt, like Sapper for the Svelte ecosystem.
Guillermo: I think these should be open platforms, because again, if everybody’s going to need this, might as well not reinvent the wheel across the entire industry, right? We very much welcome that position, we welcome people to deploy it and reconfigure it and rebuild it and redistribute it and so on.
Drew: Just recently a new version of Next.js was released, I think version 9.5. What significant changes were there in that release?
Guillermo: The most awesome one is, as I was saying earlier, a lot of things start static and then become more dynamic as things grow. This was the venture for WordPress, by the way. WordPress in the beginning was based on a static file database approach, and then grew into needing a database, kind of like what you described with how PHP evolved to be more and more MySQL. What’s nice about Next.js 9.5 is that it makes incremental static generation a production ready feature, so we took it out of the unstable flag.
Guillermo: This feature allows you to make that journey from static to dynamic without giving up on all the static benefits, and without having to go full for server-rendered dynamic, so it stretches the useful lifetime of your sort of static. The way we use it at Vercel, for example, as I mentioned, it’s like our blog gets fully pre-rendered at build time, but then for example, we’re actually in a couple minutes about to make a major announcement, and when we blog about it we want to be able to tweak it, fix it, preview it, et cetera without having to issue a five to 10-minute build every time we change one letter of one blog post.
Guillermo: With incremental static generation, you can rebuild one page at a time. What could take minutes or even seconds, depending on how big your site is, now takes milliseconds. Again, you didn’t have to give up on any of the benefits of static. That’s perhaps the thing I’m most excited about that went stable on Next.js 9.5, and specifically because the JS community and the React community and the framework community and static site generated community have been talking about this unicorn of making a static incremental for a long time, so the fact that Next.js did it, it’s being used in production and it’s there for everybody to use, I think it’s a major, major, major milestone.
Guillermo: There’s lots of little DX benefits. One that’s really nice in my opinion is Next.js, as I said, has a page system. You would argue, “Okay, so let’s say that I’m uber.com and I’ve decided to migrate on Next.js, do I need to migrate every URL inside over to Next.js in order to go live?” This has become a pretty important concern for us, because lots of people choose Next.js, but they already are running big things, so how do you reconcile the two?
Guillermo: One of the things that Next.js allows you to do in 9.5 is you can say, “I want to handle all new pages that I created with Next.js with Next.js, and the rest I want to hand off to a legacy system.” That allows you incremental, incremental is the keyword here today, incremental adoption of Next.js. You can sort of begin to strangle your legacy application with your Next.js optimized application one page at a time, when you deploy and you introduce in your Next.js page, it gets handled by Next. If it doesn’t match the Next.js routing system, it goes to the legacy system.
Drew: That sounds incredibly powerful, and the incremental rendering piece of that, I can think of several projects immediately that would really benefit that have maybe 30-minute build times for fixing a typo, as you say. That sort of technology is a big change.
Guillermo: We talked to one of the largest, I believe, use cases in Jamstack in the wild, and it was basically a documentation website and their build times were 40 minutes. We’re doing a lot in this space, by the way, like we’re making pre-rendering a lot faster as well. One of my intuitions for years to come is that as platforms get better, as the primitives get better, as the build pipelines get better we’re going to continue to extend the useful lifetime of statics. Like what ended up taking 40 minutes is going to take four.
Guillermo: A great example is we’re rolling out an incremental build cache, as well, system. I sort of pre-announced it on Twitter the other day, we’re already seeing 5.5 times faster incremental builds. One of the things that I like about Jamstack is that the core tenet is pre-render as much as possible. I do think that’s extremely valuable, because when you’re pre-rendering you’re not rendering just in time at runtime. Like what otherwise the visitor would incur in in terms of rendering costs on the server gets transferred to build time.
Guillermo: One of the most exciting things that’s coming to Next is that without you doing anything as well, the build process is also getting faster. On the Vercel side, we’re also taking advantage of some new cloud technology to make pre-rendering a lot faster as well. I think we’re always going to live in this hybrid world, but as technology gets better, build times will get better, pre-rendering will get better and faster, and then you’ll have more and more opportunities to do kind of a mix of the two.
Drew: Sounds like there’s some really exciting things coming in the future for Next.js. Is there anything else we should know before we sort of go away and get started working with Next.js?
Guillermo: Yeah. I think for a lot of people for whom this is new, you can go to nextjs.org/learn, it’ll walk you through building your first small static site with Next.js, and then it’ll walk you through the journey of adding more and more complexity over time, so it’s a really fun tutorial. I recommend also staying tuned for our announcement that I was just starting to share on twitter.com/vercel, where we share a lot of Next.js news. Specifically we highlight a lot of the work that’s being done on our open source projects and our community projects and so on. For myself as well, twitter.com/rauchg if you want to stay on top of our thoughts on the ecosystem.
Drew: I’ve been learning all about Next.js today, what have you been learning about lately, Guillermo?
Guillermo: As a random tangent that I’ve been learning about, I decided to study more economics, so I’ve been really concerned with like what is the next big thing that’s coming in terms of enabling people at scale to live better lives. I think we’re going through a transition period, especially in the US, of noticing that a lot of the institutions that people were “banking on”, like the education system, like the healthcare system, a lot of those, like where you live and whether you’re going to own a house or rent and things like that, a lot of these things are changing, they have changed rapidly, and people have lost their compass.
Guillermo: Things like, “Oh, should I go to college? Should I get a student loan?” and things like that, and there is a case to be made for capitalism 3.0, and there is a case to be made for next level of evolution in social and economic systems. I’ve been just trying to expand my horizons in learning a lot more about what could be next, no pun intended. I’ve found there’s lots of great materials and lots of great books. A lot of people have been thinking about this problem, and there is lots of interesting solutions in the making.
Drew: That’s fascinating. If you, dear listener, would like to hear more from Guillermo, you can find him on Twitter at @RauchG, and you can find more about Next.js and keep up to date with everything that goes on in that space at nextjs.org. Thanks for joining us today, Guillermo. Do you have any parting words?
Guillermo: No, thank you for having me.
(il)
Website Design & SEO Delray Beach by DBL07.co
Delray Beach SEO
source http://www.scpie.org/smashing-podcast-episode-23-with-guillermo-rauch-what-is-next-js/ source https://scpie1.blogspot.com/2020/08/smashing-podcast-episode-23-with.html
0 notes
riichardwilson · 5 years ago
Text
Smashing Podcast Episode 23 With Guillermo Rauch: What Is Next.js?
We’re talking about Next.js. What is it, and where might it fit into our web development workflow? Drew McLellan talks to co-creator Guillermo Rauch to find out.
Today, We’re talking about Next.js. What is it, and where might it fit into our web development workflow? I spoke to co-creator Guillermo Rauch to find out.
Show Notes
Weekly Update
Transcript
Drew McLellan: He’s the founder and CEO of Vercel, a cloud platform for static sites that fits around a Jamstack workflow. He’s also the co-creator of Next.js. He previously founded LearnBoost and CloudUp, and is well-known as the creator of several popular node open source libraries like Socket.io, Mongoose, and SlackIn. Prior to that, he was a core developer on MooTools, so we know he knows his way around JavaScript like the back of his hand. Did you know he once received a royal commission from the King of Spain to create an ice sculpture out of iceberg lettuce? My smashing friends, please welcome Guillermo Rauch. Hi Guillermo, how are you?
Guillermo Rauch: I’m smashing freaking good, thanks for having me.
Drew: I wanted to talk to you today about the whole world of Next.js, as it’s something that obviously you’re personally very knowledgeable about, having been involved as a co-creator right from the start. Next.js is one of those project names that has been on my radar while working in the Jamstack space, but it isn’t something that I’ve actually personally looked at or worked with too closely before. For people who are like me, who perhaps aren’t aware of what Next.js is, perhaps you could give us a bit of background into what it is and what problems it tries to solve.
Guillermo: Next.js is a very interesting member of the Jamstack universe, because Next.js actually started being a fully SSR-focused framework. It started getting a lot of adoption outside the Jamstack space where people were building very large things specifically when they wanted to have user generated content or dynamic content or social networks or e-commerce, and they knew that they wanted SSR because their data set was very large or very dynamic. It fell under the radar I think for a lot of people in the Jamstack world, but later on Next.js gained the capabilities for static optimization.
Guillermo: On one hand, for example, if you wouldn’t do data fetching at the top level of your page with Next.js, your React page would be … Also by the way, for those who are not fully in the know, Next.js is simply React framework for production, but has this capability of doing some rendering. Then when you get in static optimization capabilities, if you wouldn’t define data fetching at the top level of your page, it automatically exported as HTML instead of trying to do anything with server rendering.
Guillermo: Then later on, it also gained the capability for static site generation, meaning that you can define a special data hook, but that data hook gets data at build time. Next.js became a hybrid, very powerful dynamic and static framework, and now it’s been growing a lot in the Jamstack space as well.
Drew: People might say that React is already a framework, you certainly hear it described that way. What does it actually mean to be a framework for React?
Guillermo: That’s a great observation, because I always point out to people that React at Facebook and React outside of Facebook are completely different beasts. React at Facebook actually is used together with server rendering, but even their server rendering, for example, doesn’t use Node.js, it uses a highly specialized virtual machine called Hermes which communicates to their sort of production hack and PHP stack and answers all this advanced and exotic Facebook needs.
Guillermo: When they open source React, it’s almost like open sourcing a component. I always call it like open sourcing the engine, but not giving you the car. What happened is people really wanted to go and drive with it, they wanted to get to places with React. In the community, people started creating cars, and they would embed React as the engine, which was what the driver, the developer was after in the first place, make React the fundamental part of the car. Things like Next.js and Gatsby and React Static and many other frameworks started appearing that were solving the need for like, “I actually want to create fully loaded pages and applications.”
Guillermo: Whereas React was kind of more like the component and the engine for specific widgets within the page, this was certainly the case for Facebook. They will broadly and publicly admit that they invented it for things like the notification batch, the chat widget, the newsfeed component, and those components were React routes that were embedded into the contents of the production existing app with lots and lots of lines of code and even other JS libraries and frameworks.
Guillermo: What it means to create a framework for React, it means you make React the fundamental part of the story, hopefully and this is something we’ll try to do with Next.js, the learning curve is primarily about React with some added surface for Next.js, particularly around data fetching and routing. We also do a lot of production optimizations, so when you get React, when you get Create React app, which is sort of like, I like to call it a bootstrapped car that Facebook gives you, maybe the needs for production are not really met. Or if you try to do it yourself by configuring Webpack and configuring Babel and configuring server rendering and static generation, it’s also hard to put together a car from scratch. Next.js will give you this zero config and also production optimized set of defaults around building entire big things with React.
Drew: So it’s like it almost puts a sort of ecosystem around your React app with a collection of pre-configured tools to enable you to-
Guillermo: Correct.
Drew: Hit the ground running and do static site generation or server rendering or routing.
Guillermo: Correct, and you used a word there that is very, very key to all this, which is pre-configured. We’re fortunate enough to draw the attention of Google Chrome as a contributor to Next.js. One of the leaders of this project, her thing is that when they were working on frameworks internally at Google, they faced a lot of the same problems that the community and open source are facing today. There were many different competing initiatives at Google on how to scale and make really performant web apps out of the box.
Guillermo: You would join as a Googler and you would be given a framework with which you would create really big production ready, very high performance applications. Shubie was part of a lot of those initiatives, and what she found is that there’s two key ingredients to making a framework succeed at scale. One is pre-configuration, meaning that you come to work, you’re going to start a brand new app, you should be given something that is already ready to go and meets a lot of the production demands that are known at that given point in time.
Guillermo: On the other hand, the other really important step that we’re working towards is conformance. You can be given the most highly optimized production ready pre-configured framework, but if you go ahead and, for example, start introducing lots of heavy dependencies or third party scripts or use very inefficient layouts that take a long time to paint and so on and so forth, then you’re going to make that pre-configuration sort of go to waste. By mixing pre-configuration with conformance over time, the developer is not only having a great starting point, but it’s also guided to success over time.
Drew: It seems that a characteristic of Next.js, that it’s quite opinionated, the UI layer is React, it uses type script, uses Webpack, and those are all choices that the project has made and that’s what you get. Correct me if I’m wrong, but you couldn’t swap out React for Vue, for example, within Next.js.
Guillermo: That’s a good point, where technical decision making meets sort of an art. On one hand, I’d really like to claim that Next is very unopinionated, and the reason for this is that if you specifically go to github.com/vercel/nextjs and the examples directory, you’ll see that there’s almost like a combinatoric explosion of technologies that you can use together with Next.js. You’ll see fire-based, you’ll see Graphic UL, you’ll see Apollo, you’ll see RedUX, you’ll see MobX, in the CSS space there’s even more options.
Guillermo: We have a default CSS port that’s embedded, but then you can use two flavors of it, one with import, one with style tags which we call Style JSX, which resembles very much like the web platform approach to Shadow CSS. The reason I mean unopinionated is we want Next.js to stay very close to the “bare metal” of the web, and not introduce lots of primitives that if the web from 10 years from today would be incompatible with. Then if you look at the examples, you’ll see that there’s all these other technologies that you can plug in.
Guillermo: The base level of opinionation is that there is React and you’re not going to be able to replace it, at least anytime soon. Then there is the concept of you should be able to create pages, and this was kind of like a new thing when we first launched it, which was everyone is trying to create single-page applications. What we realized is like the internet is made up of websites with lots of pages that create distinct entry points via search engines, via Twitter, via Facebook, via social networks, via email companions, like you always guide the person toward an entry point, and that person that comes through that entry point shouldn’t have to download the burden of the entirety of the application.
Guillermo: Then that path led us to implementing server rendering, then static generation for multiple pages, et cetera, et cetera. That other base level of opinionation is Next should be a framework that works for the web, not against the web. Then on top of that, React was missing data fetching and routing primitives, and we added those. There’s a level of opinionation that has to deal with like everybody needs a router, so might as well have a router built in by default.
Drew: The big advantage of having those defaults is it takes away a lot of the complexity of choice, that it’s just there, it’s configured, and you can just start using it without needing to think too much, because I think we’ve all-
Guillermo: Exactly.
Drew: Been in situations where there are far too many choices of what components to use, and it can be overwhelming and get in the way of being productive.
Guillermo: Exactly.
Drew: What sort of projects do you see people using Next.js for? Is it for basically any situation where you might build a production React app, or is it more suited to particular types of content heavy sites? Does it matter in that sense?
Guillermo: Yeah, so this has been an age old debate of the web, is the web for apps, is the web for sites, is it a hybrid? What is the role of JavaScript, et cetera, et cetera? It’s kind of hard to give a straight up answer, but my take on this is the web was evolved always to be a hybrid of content that is evolving to be more and more dynamic and personal to the user. Even when you say like a content website, the high end content websites of the world have code bases that are very much comparable to apps.
Guillermo: A great example here is like New York Times, they’ll give you embedded widgets with data analysis tools and interactive animation, and they’ll recommend what story to read next, and they have a subscription model built in which sometimes gives you part of the content and sometimes counts how many articles you’ve read. Like if I told you this when the web was invented, like Tim Berners-Lee would be like, “No, that’s crazy, that’s not possible on the web,” but that’s the web we have today.
Guillermo: Next.js is answering a lot of these complex modern needs, which means you’ll see lots of e-commerce usage, you’ll see lots of content with that. E-commerce meaning, by the way, not just like buy items, but experiences like the largest real estate websites on the web, realtor.com, zillow.com, trulio.com, that entire category is all Next.js, then content sites. We just onboarded washingtonpost.com as a customer of Vercel and Next.js, we have then a third category that is more emergent but very interesting, which is full apps and user-generated content, like tiktok.com, and kind of like you would think the original single-page application use case as well being quite represented there.
Guillermo: Next.js sort of shines when you need to have lots of content that has to be served very, very quickly, has to be SEO Company optimized, and at the end of the day, it’s a mix of dynamic and static.
Drew: I’ve previously spoken to Marcy Sutton about Gatsby, which seems to be in a similar sort of space. It’s always great to see more than one solution to a problem and having choice for one project to the next. Would you say that Next.js and Gatsby are operating in the same sort of problem space, and how similar or dissimilar are they?
Guillermo: I think there’s an overlap for some use cases. For example, my personal blog rauchg.com runs on Next.js, it could’ve just been a great Gatsby blog as well. There is that overlap in the smaller static website sort of space, and by small I don’t mean not relevant. A lot of dotcoms that are super, super important run on basically static web, so that’s the beauty of Jamstack in my opinion. Because Next.js can statically optimize your pages and then you can get great Lighthouse scores through that, you can use it for overlapping use cases.
Guillermo: I think the line gets drawn when you start going into more dynamic needs and you have lots of pages, you have the need to update them at one time. Although Gatsby is creating solutions for those, Next.js already has production ready live solutions that work with any sort of database, any sort of data backend for basically “generating” or “printing” lots and lots of pages. That’s where today customers are going to Next.js instead of Gatsby.
Drew: One of the problems that everyone seems to run into as their JavaScript-based solution gets bigger is performance and how things can start getting pretty slow, you have big bundle sizes. Traditionally, things like code splitting can be fairly complex to get configured correctly. I see that’s one of the features that jumped out at me of Next.js, that it claims that the code splitting is automatic. What does Next.js do in terms of code splitting to make that work?
Guillermo: Your observation is 100% right. One of the biggest things with the web and one of the biggest weights on the web is JavaScript, and just like different materials have different densities and weights irrespective of the actual physical volume, JavaScript tends to be a very dense, heavy element. Even small amounts of JavaScript compared to, like for example, images that can be processed asynchronously and off the main thread, JavaScript tends to be particularly bothersome.
Guillermo: Next.js has invested a tremendous amount of effort into automatically optimizing your bundles. The first one that was my first intuition when I first came up with the idea for Next.js was you’re going to define, for example, 10 routes. In the Next.js world you create a pages directory and you drop your files in there Index.js, About.js, Settings.js, Dashboard.js, Termsofservice.js, Signup.js, Login.js. Those become entry points to your application that you can share through all kinds of media.
Guillermo: When you enter those, we want to give you JS that is relevant for that page first and foremost, and then perhaps a common bundle so that subsequent navigations within the system are very snappy. Next.js also, which is very, very nice, automatically pre-fetches the rest of the pages that are connected to that entry point, such that it feels like a single-page application. A lot of people say like, “Why not just use Create React app if I know that I have maybe a couple routes?” I always tell them, “Look, you can find those as pages, and because Next.js will automatically pre-fetch ones that are connected, you end up getting your single-page application, but it’s better optimized with regards to that initial paint, that initial entry point.”
Guillermo: That was the initial code splitting approach, but then it became a lot more sophisticated over time. Google contributed a very nice optimization called Module and No Module, which will give differential JS to modern browsers, and legacy JS that’s heavy with polyfields to other browsers, and this optimization 100% automated and produces massive savings. We gave it to one of our customers that we host on Vercel called Parnaby’s, I believe if I’m not mistaken, it was something very, very significant. It was maybe like 30% savings in code sizes, and that was just because they upgraded Next.js to a version that optimized JS bundles better.
Guillermo: That was kind of the point that we were going over earlier, which is you choose Next.js and it only gets better and more optimal over time, it’ll continue to optimize things on your behalf. Those are, again, pre-configurations that you would never have to deal with or be bothered with, and the research of which you don’t ever even want to do, to be honest. Like I wasn’t obviously very involved with this, but I look at some of the internal discussions and they were discussing all these polyfields that only mattered to Internet Explorer X and Soho, I was like, “I don’t even want to know, let’s just upgrade Next.js and get all these benefits.”
Drew: There is sometimes great benefits on there with sticking with the defaults and sticking with the most common configuration of things, which seems to be really the Next.js approach. I remember when I started writing PHP back in the early 2000s, and everybody was using PHP and MySQL, and at the time I’d just come from Windows so I wanted to use PHP and Microsoft Sequel Server. You can do it, but you’re swimming against the tide the whole way. Then as soon as I just switched over to MySQL, the whole ecosystem just started working for me and I didn’t need to think about it.
Guillermo: Yeah, everything just clicks, that is such a great observation. We see that all the time, like the Babel ecosystem is so powerful now that you could become, for example, a little bit faster by swapping Babel for something else, but then you trade off that incredible ecosystem compatibility. This is something you touched on performance earlier, and like for a lot of people, build performance and static generation performance is a big bottleneck, and this is something that we are very diligent in improving the performance of our tools incrementally.
Guillermo: For example, one of the things that Next.js is doing now is that it’s upgrading its default from Webpack 4 to Webpack 5, which has some breaking things, and that’s why we’re first offering it to people as an opt-in flag, but later on it’ll become the default. Webpack 5 makes incredible performance improvements, but we’re not sacrificing the Webpack ecosystem, we incrementally improved. Sure, there were some very small things that needed to be sacrificed, but that’s an incredible benefit of the JS ecosystem today that a lot of people are glossing over, I think, because maybe they see, “Oh, we could’ve done X in Soho, maybe it was a little faster, or maybe MPM in Soho would take less time.” They pick up some details and they miss the bigger picture, which is the ecosystem value is enormous.
Drew: The value of having all the configuration and the maintenance and that side of it done by a project like Next.js rather than taking that on yourself by swapping to using something else is incredible, because as soon as you move away from those defaults, you’re taking on the burden of keeping all the compatibilities going and doing it yourself. One of the things that I’ve been really interested in with Next.js is there are options available for either doing static site generation or server-side rendering, or maybe a hybrid of the two perhaps. I think there’s been some recent changes to this in a recent update, can you tell us a little bit about that and when you might choose one or the other?
Guillermo: Yeah, for sure. One of the key components of this hybrid approach combined with the page system that I described earlier is that you can have pages that are fully static or pages that server rendered. A page that’s fully static has the incredible benefit of what I call static hoisting, which is you can take that asset and automatically put it at the edge. By putting it at the edge, I mean you can cache it, you can preemptively cache it, you can replicate it, you can make it so that when a request comes in, it never touches the server because we know ahead of time, “Hey, Slash Index is a static.”
Guillermo: That’s a very, very interesting benefit when it comes down to serving global audiences. You basically get an automatic CDN out of the box, especially when you deploy the modern edge networks like Vercel or AWS Amplify or Netlify and so on. Next.js has this premise of if it can be made static, it should be static. When you’re first starting a project and you’re working on your first page or you’re kicking the tires of the framework, might as well make everything static.
Guillermo: Even for high end needs, so for example, vercel.com, our own usage of Next.js is fully static. It’s a combination of fully static and static site generation, so all our marketing agency pages are static, our blog is statically generated from a dynamic data source, and then our dashboard which has lots of dynamic data, but we can deliver it as shells or skeletons, all the pages associated with viewing your deployments, viewing your projects, viewing your logs, et cetera, et cetera, are all basically static pages with client-side JavaScript.
Guillermo: That serves us incredibly well because everything where we need a very fast first-pane performance is already pre-rendered, everything that needs SEO Company, already pre-rendered, and everything that’s extremely dynamic, we only have to worry about security, for example, from the perspective of the client side which uses the same API calls that, for example, our CLI used or our integrations use, et cetera, et cetera. A fully static website, very cheap to operate, incredibly scalable and so on and so forth.
Guillermo: Now, one particular thing that we needed with our blog was we wanted to update the data very quickly. We wanted to fix a typo very quickly and not wait for an entire build to happen, and this is a very significant benefit of Next.js, that as you straddle from a static to a dynamic, it gives you these in between solutions as well. For our blog we used incremental static generation, so essentially we can rebuild one page at a time when the underlying content changes.
Guillermo: Imagine that we had not just a couple hundred blog posts and we had lots of blog posts being generated all the time and being updated all the time, like I mentioned one of our customers, Washington Post, in that case you need to go more toward full SSR, especially as you start customizing the content for each user. That journey of complexity that I just described started from I have one marketing agency page, to I have a blog that has a couple thousand pages, to I have tens of thousands or millions of pages. That’s the Next.js journey that you can traverse with your own business.
Guillermo: Then you start as a developer to choose between perhaps less responsibility to more responsibility, because when you opt in to using SSR, you’re now executing code on the server, you’re executing code on the cloud, there’s more responsibility with more power. The fact that you can decide where you use each kind of tool is I think a very, very interesting benefit of Next.
Drew: Just in practicalities of combining the static site generation and the server-side rendering, how does that work in terms of the server element? Are you needing a dedicated platform like Vercel to be able to achieve that, or is that something that can be done more straightforwardly and more simply?
Guillermo: Next.js gives you a dev server, so you download Next and you run your Next Dev, and that’s the dev server. The dev server is obviously incredibly optimized for development, like it has the latest fast refresh technology that Facebook released, where … Actually, Facebook didn’t release it, Facebook uses it internally to get the best and most performant and most reliable hot module replacement, such that you’re basically typing and it changes are reflecting on the screen, so that’s the dev server.
Guillermo: Then Next gives you a production server called Next Start, and Next Start has all the capabilities of the framework for self-hosting. The interesting thing about Vercel is that when you deploy Next to it, it gets automatically optimized and it’s 100% serverless, meaning there’s no responsibility whatsoever of administration, scaling, cashing and cashing validation, purging, replication, global fail over and so on and so forth that you would have to take on when you run Next Start yourself.
Guillermo: That’s also the great benefit of Next.js, so for example, apple.com has several different properties, subdomains and pages on dotcom on Next.js they self-host, due to very, very advanced and stringent security and privacy needs. On the other hand, washingtonpost.com uses Vercel, so we have this sort of wide range of users, and we’re extremely happy to support all of them. The nice thing about where serverless is headed in my opinion is it can give you best of both worlds in terms of the most optimal performance that only gets better over time, with the best developer experience of like, “Hey, I don’t have to worry about any sort of infrastructure.”
Drew: The Next.js is an open source project that’s being developed by the team at Vercel. Are there other contributors outside of Vercel?
Guillermo: Yeah, so Google Chrome being the main one that actively submit server PRs, help us with optimizations and testing it with partners, like very large Next.js users that are already part of the Google ecosystem, for example, due to using lots and lots of apps, so they need to be involved closely as partners. Facebook, we maintain a great relationship with the Facebook team. For example, fast refresh, we were the first React framework to land that, and they helped guide us through all the things that they learned of using React and fast refresh at Facebook.
Guillermo: We work with lots of partners that have very large deployments of Next.js apps in the wild from all kinds of different sort of use cases, like imagine e-commerce and content. Then there’s just lots and lots of independent contributors, people that use Next.js personally, but also educators and members of front infrastructure teams at large companies. It’s a very, very wide community effort.
Drew: It sounds like the concern that somebody might have, that this is being developed in a significant part by Vercel, that they might have the concern that they’re going to get sort of locked into deploying on that particular platform, but it sounds very much like that’s not the case at all, and they could develop a site and deploy it on Firebase or Netlify or…
Guillermo: Yeah, absolutely. I like to compare it a lot for like the Kubernetes of the Front End age in a way, because at the end of the day I am a firm believer that … Kubernetes is something that pretty much almost everyone needs when they need to run LinUX processes, like you were talking about opinionation and you’re saying it’s a good technology, it’s very much not opinionated, but there is some opinionation that we kind of forget about. It’s like at the end of the day, it grew out of running a specific demons of LinUX programs packaged as containers.
Guillermo: Next is in a similar position, because what we take for being the universal primitive of the world as a React component, obviously it’s opinionated, but we do think that for lots of enterprises, just like they all gravitate towards LinUX, we are seeing the same thing towards React and Vue, but Vue luckily has NUXt too, which is a very awesome solution, it’s equivalent in ideation and principles as Next. We’re gravitating towards these platforms like Next.js, like NUXt, like Sapper for the Svelte ecosystem.
Guillermo: I think these should be open platforms, because again, if everybody’s going to need this, might as well not reinvent the wheel across the entire industry, right? We very much welcome that position, we welcome people to deploy it and reconfigure it and rebuild it and redistribute it and so on.
Drew: Just recently a new version of Next.js was released, I think version 9.5. What significant changes were there in that release?
Guillermo: The most awesome one is, as I was saying earlier, a lot of things start static and then become more dynamic as things grow. This was the venture for WordPress, by the way. WordPress in the beginning was based on a static file database approach, and then grew into needing a database, kind of like what you described with how PHP evolved to be more and more MySQL. What’s nice about Next.js 9.5 is that it makes incremental static generation a production ready feature, so we took it out of the unstable flag.
Guillermo: This feature allows you to make that journey from static to dynamic without giving up on all the static benefits, and without having to go full for server-rendered dynamic, so it stretches the useful lifetime of your sort of static. The way we use it at Vercel, for example, as I mentioned, it’s like our blog gets fully pre-rendered at build time, but then for example, we’re actually in a couple minutes about to make a major announcement, and when we blog about it we want to be able to tweak it, fix it, preview it, et cetera without having to issue a five to 10-minute build every time we change one letter of one blog post.
Guillermo: With incremental static generation, you can rebuild one page at a time. What could take minutes or even seconds, depending on how big your site is, now takes milliseconds. Again, you didn’t have to give up on any of the benefits of static. That’s perhaps the thing I’m most excited about that went stable on Next.js 9.5, and specifically because the JS community and the React community and the framework community and static site generated community have been talking about this unicorn of making a static incremental for a long time, so the fact that Next.js did it, it’s being used in production and it’s there for everybody to use, I think it’s a major, major, major milestone.
Guillermo: There’s lots of little DX benefits. One that’s really nice in my opinion is Next.js, as I said, has a page system. You would argue, “Okay, so let’s say that I’m uber.com and I’ve decided to migrate on Next.js, do I need to migrate every URL inside over to Next.js in order to go live?” This has become a pretty important concern for us, because lots of people choose Next.js, but they already are running big things, so how do you reconcile the two?
Guillermo: One of the things that Next.js allows you to do in 9.5 is you can say, “I want to handle all new pages that I created with Next.js with Next.js, and the rest I want to hand off to a legacy system.” That allows you incremental, incremental is the keyword here today, incremental adoption of Next.js. You can sort of begin to strangle your legacy application with your Next.js optimized application one page at a time, when you deploy and you introduce in your Next.js page, it gets handled by Next. If it doesn’t match the Next.js routing system, it goes to the legacy system.
Drew: That sounds incredibly powerful, and the incremental rendering piece of that, I can think of several projects immediately that would really benefit that have maybe 30-minute build times for fixing a typo, as you say. That sort of technology is a big change.
Guillermo: We talked to one of the largest, I believe, use cases in Jamstack in the wild, and it was basically a documentation website and their build times were 40 minutes. We’re doing a lot in this space, by the way, like we’re making pre-rendering a lot faster as well. One of my intuitions for years to come is that as platforms get better, as the primitives get better, as the build pipelines get better we’re going to continue to extend the useful lifetime of statics. Like what ended up taking 40 minutes is going to take four.
Guillermo: A great example is we’re rolling out an incremental build cache, as well, system. I sort of pre-announced it on Twitter the other day, we’re already seeing 5.5 times faster incremental builds. One of the things that I like about Jamstack is that the core tenet is pre-render as much as possible. I do think that’s extremely valuable, because when you’re pre-rendering you’re not rendering just in time at runtime. Like what otherwise the visitor would incur in in terms of rendering costs on the server gets transferred to build time.
Guillermo: One of the most exciting things that’s coming to Next is that without you doing anything as well, the build process is also getting faster. On the Vercel side, we’re also taking advantage of some new cloud technology to make pre-rendering a lot faster as well. I think we’re always going to live in this hybrid world, but as technology gets better, build times will get better, pre-rendering will get better and faster, and then you’ll have more and more opportunities to do kind of a mix of the two.
Drew: Sounds like there’s some really exciting things coming in the future for Next.js. Is there anything else we should know before we sort of go away and get started working with Next.js?
Guillermo: Yeah. I think for a lot of people for whom this is new, you can go to nextjs.org/learn, it’ll walk you through building your first small static site with Next.js, and then it’ll walk you through the journey of adding more and more complexity over time, so it’s a really fun tutorial. I recommend also staying tuned for our announcement that I was just starting to share on twitter.com/vercel, where we share a lot of Next.js news. Specifically we highlight a lot of the work that’s being done on our open source projects and our community projects and so on. For myself as well, twitter.com/rauchg if you want to stay on top of our thoughts on the ecosystem.
Drew: I’ve been learning all about Next.js today, what have you been learning about lately, Guillermo?
Guillermo: As a random tangent that I’ve been learning about, I decided to study more economics, so I’ve been really concerned with like what is the next big thing that’s coming in terms of enabling people at scale to live better lives. I think we’re going through a transition period, especially in the US, of noticing that a lot of the institutions that people were “banking on”, like the education system, like the healthcare system, a lot of those, like where you live and whether you’re going to own a house or rent and things like that, a lot of these things are changing, they have changed rapidly, and people have lost their compass.
Guillermo: Things like, “Oh, should I go to college? Should I get a student loan?” and things like that, and there is a case to be made for capitalism 3.0, and there is a case to be made for next level of evolution in social and economic systems. I’ve been just trying to expand my horizons in learning a lot more about what could be next, no pun intended. I’ve found there’s lots of great materials and lots of great books. A lot of people have been thinking about this problem, and there is lots of interesting solutions in the making.
Drew: That’s fascinating. If you, dear listener, would like to hear more from Guillermo, you can find him on Twitter at @RauchG, and you can find more about Next.js and keep up to date with everything that goes on in that space at nextjs.org. Thanks for joining us today, Guillermo. Do you have any parting words?
Guillermo: No, thank you for having me.
(il)
Website Design & SEO Delray Beach by DBL07.co
Delray Beach SEO
source http://www.scpie.org/smashing-podcast-episode-23-with-guillermo-rauch-what-is-next-js/ source https://scpie.tumblr.com/post/627461427437928448
0 notes
scpie · 5 years ago
Text
Smashing Podcast Episode 23 With Guillermo Rauch: What Is Next.js?
We’re talking about Next.js. What is it, and where might it fit into our web development workflow? Drew McLellan talks to co-creator Guillermo Rauch to find out.
Today, We’re talking about Next.js. What is it, and where might it fit into our web development workflow? I spoke to co-creator Guillermo Rauch to find out.
Show Notes
Weekly Update
Transcript
Drew McLellan: He’s the founder and CEO of Vercel, a cloud platform for static sites that fits around a Jamstack workflow. He’s also the co-creator of Next.js. He previously founded LearnBoost and CloudUp, and is well-known as the creator of several popular node open source libraries like Socket.io, Mongoose, and SlackIn. Prior to that, he was a core developer on MooTools, so we know he knows his way around JavaScript like the back of his hand. Did you know he once received a royal commission from the King of Spain to create an ice sculpture out of iceberg lettuce? My smashing friends, please welcome Guillermo Rauch. Hi Guillermo, how are you?
Guillermo Rauch: I’m smashing freaking good, thanks for having me.
Drew: I wanted to talk to you today about the whole world of Next.js, as it’s something that obviously you’re personally very knowledgeable about, having been involved as a co-creator right from the start. Next.js is one of those project names that has been on my radar while working in the Jamstack space, but it isn’t something that I’ve actually personally looked at or worked with too closely before. For people who are like me, who perhaps aren’t aware of what Next.js is, perhaps you could give us a bit of background into what it is and what problems it tries to solve.
Guillermo: Next.js is a very interesting member of the Jamstack universe, because Next.js actually started being a fully SSR-focused framework. It started getting a lot of adoption outside the Jamstack space where people were building very large things specifically when they wanted to have user generated content or dynamic content or social networks or e-commerce, and they knew that they wanted SSR because their data set was very large or very dynamic. It fell under the radar I think for a lot of people in the Jamstack world, but later on Next.js gained the capabilities for static optimization.
Guillermo: On one hand, for example, if you wouldn’t do data fetching at the top level of your page with Next.js, your React page would be … Also by the way, for those who are not fully in the know, Next.js is simply React framework for production, but has this capability of doing some rendering. Then when you get in static optimization capabilities, if you wouldn’t define data fetching at the top level of your page, it automatically exported as HTML instead of trying to do anything with server rendering.
Guillermo: Then later on, it also gained the capability for static site generation, meaning that you can define a special data hook, but that data hook gets data at build time. Next.js became a hybrid, very powerful dynamic and static framework, and now it’s been growing a lot in the Jamstack space as well.
Drew: People might say that React is already a framework, you certainly hear it described that way. What does it actually mean to be a framework for React?
Guillermo: That’s a great observation, because I always point out to people that React at Facebook and React outside of Facebook are completely different beasts. React at Facebook actually is used together with server rendering, but even their server rendering, for example, doesn’t use Node.js, it uses a highly specialized virtual machine called Hermes which communicates to their sort of production hack and PHP stack and answers all this advanced and exotic Facebook needs.
Guillermo: When they open source React, it’s almost like open sourcing a component. I always call it like open sourcing the engine, but not giving you the car. What happened is people really wanted to go and drive with it, they wanted to get to places with React. In the community, people started creating cars, and they would embed React as the engine, which was what the driver, the developer was after in the first place, make React the fundamental part of the car. Things like Next.js and Gatsby and React Static and many other frameworks started appearing that were solving the need for like, “I actually want to create fully loaded pages and applications.”
Guillermo: Whereas React was kind of more like the component and the engine for specific widgets within the page, this was certainly the case for Facebook. They will broadly and publicly admit that they invented it for things like the notification batch, the chat widget, the newsfeed component, and those components were React routes that were embedded into the contents of the production existing app with lots and lots of lines of code and even other JS libraries and frameworks.
Guillermo: What it means to create a framework for React, it means you make React the fundamental part of the story, hopefully and this is something we’ll try to do with Next.js, the learning curve is primarily about React with some added surface for Next.js, particularly around data fetching and routing. We also do a lot of production optimizations, so when you get React, when you get Create React app, which is sort of like, I like to call it a bootstrapped car that Facebook gives you, maybe the needs for production are not really met. Or if you try to do it yourself by configuring Webpack and configuring Babel and configuring server rendering and static generation, it’s also hard to put together a car from scratch. Next.js will give you this zero config and also production optimized set of defaults around building entire big things with React.
Drew: So it’s like it almost puts a sort of ecosystem around your React app with a collection of pre-configured tools to enable you to-
Guillermo: Correct.
Drew: Hit the ground running and do static site generation or server rendering or routing.
Guillermo: Correct, and you used a word there that is very, very key to all this, which is pre-configured. We’re fortunate enough to draw the attention of Google Chrome as a contributor to Next.js. One of the leaders of this project, her thing is that when they were working on frameworks internally at Google, they faced a lot of the same problems that the community and open source are facing today. There were many different competing initiatives at Google on how to scale and make really performant web apps out of the box.
Guillermo: You would join as a Googler and you would be given a framework with which you would create really big production ready, very high performance applications. Shubie was part of a lot of those initiatives, and what she found is that there’s two key ingredients to making a framework succeed at scale. One is pre-configuration, meaning that you come to work, you’re going to start a brand new app, you should be given something that is already ready to go and meets a lot of the production demands that are known at that given point in time.
Guillermo: On the other hand, the other really important step that we’re working towards is conformance. You can be given the most highly optimized production ready pre-configured framework, but if you go ahead and, for example, start introducing lots of heavy dependencies or third party scripts or use very inefficient layouts that take a long time to paint and so on and so forth, then you’re going to make that pre-configuration sort of go to waste. By mixing pre-configuration with conformance over time, the developer is not only having a great starting point, but it’s also guided to success over time.
Drew: It seems that a characteristic of Next.js, that it’s quite opinionated, the UI layer is React, it uses type script, uses Webpack, and those are all choices that the project has made and that’s what you get. Correct me if I’m wrong, but you couldn’t swap out React for Vue, for example, within Next.js.
Guillermo: That’s a good point, where technical decision making meets sort of an art. On one hand, I’d really like to claim that Next is very unopinionated, and the reason for this is that if you specifically go to github.com/vercel/nextjs and the examples directory, you’ll see that there’s almost like a combinatoric explosion of technologies that you can use together with Next.js. You’ll see fire-based, you’ll see Graphic UL, you’ll see Apollo, you’ll see RedUX, you’ll see MobX, in the CSS space there’s even more options.
Guillermo: We have a default CSS port that’s embedded, but then you can use two flavors of it, one with import, one with style tags which we call Style JSX, which resembles very much like the web platform approach to Shadow CSS. The reason I mean unopinionated is we want Next.js to stay very close to the “bare metal” of the web, and not introduce lots of primitives that if the web from 10 years from today would be incompatible with. Then if you look at the examples, you’ll see that there’s all these other technologies that you can plug in.
Guillermo: The base level of opinionation is that there is React and you’re not going to be able to replace it, at least anytime soon. Then there is the concept of you should be able to create pages, and this was kind of like a new thing when we first launched it, which was everyone is trying to create single-page applications. What we realized is like the internet is made up of websites with lots of pages that create distinct entry points via search engines, via Twitter, via Facebook, via social networks, via email companions, like you always guide the person toward an entry point, and that person that comes through that entry point shouldn’t have to download the burden of the entirety of the application.
Guillermo: Then that path led us to implementing server rendering, then static generation for multiple pages, et cetera, et cetera. That other base level of opinionation is Next should be a framework that works for the web, not against the web. Then on top of that, React was missing data fetching and routing primitives, and we added those. There’s a level of opinionation that has to deal with like everybody needs a router, so might as well have a router built in by default.
Drew: The big advantage of having those defaults is it takes away a lot of the complexity of choice, that it’s just there, it’s configured, and you can just start using it without needing to think too much, because I think we’ve all-
Guillermo: Exactly.
Drew: Been in situations where there are far too many choices of what components to use, and it can be overwhelming and get in the way of being productive.
Guillermo: Exactly.
Drew: What sort of projects do you see people using Next.js for? Is it for basically any situation where you might build a production React app, or is it more suited to particular types of content heavy sites? Does it matter in that sense?
Guillermo: Yeah, so this has been an age old debate of the web, is the web for apps, is the web for sites, is it a hybrid? What is the role of JavaScript, et cetera, et cetera? It’s kind of hard to give a straight up answer, but my take on this is the web was evolved always to be a hybrid of content that is evolving to be more and more dynamic and personal to the user. Even when you say like a content website, the high end content websites of the world have code bases that are very much comparable to apps.
Guillermo: A great example here is like New York Times, they’ll give you embedded widgets with data analysis tools and interactive animation, and they’ll recommend what story to read next, and they have a subscription model built in which sometimes gives you part of the content and sometimes counts how many articles you’ve read. Like if I told you this when the web was invented, like Tim Berners-Lee would be like, “No, that’s crazy, that’s not possible on the web,” but that’s the web we have today.
Guillermo: Next.js is answering a lot of these complex modern needs, which means you’ll see lots of e-commerce usage, you’ll see lots of content with that. E-commerce meaning, by the way, not just like buy items, but experiences like the largest real estate websites on the web, realtor.com, zillow.com, trulio.com, that entire category is all Next.js, then content sites. We just onboarded washingtonpost.com as a customer of Vercel and Next.js, we have then a third category that is more emergent but very interesting, which is full apps and user-generated content, like tiktok.com, and kind of like you would think the original single-page application use case as well being quite represented there.
Guillermo: Next.js sort of shines when you need to have lots of content that has to be served very, very quickly, has to be SEO Company optimized, and at the end of the day, it’s a mix of dynamic and static.
Drew: I’ve previously spoken to Marcy Sutton about Gatsby, which seems to be in a similar sort of space. It’s always great to see more than one solution to a problem and having choice for one project to the next. Would you say that Next.js and Gatsby are operating in the same sort of problem space, and how similar or dissimilar are they?
Guillermo: I think there’s an overlap for some use cases. For example, my personal blog rauchg.com runs on Next.js, it could’ve just been a great Gatsby blog as well. There is that overlap in the smaller static website sort of space, and by small I don’t mean not relevant. A lot of dotcoms that are super, super important run on basically static web, so that’s the beauty of Jamstack in my opinion. Because Next.js can statically optimize your pages and then you can get great Lighthouse scores through that, you can use it for overlapping use cases.
Guillermo: I think the line gets drawn when you start going into more dynamic needs and you have lots of pages, you have the need to update them at one time. Although Gatsby is creating solutions for those, Next.js already has production ready live solutions that work with any sort of database, any sort of data backend for basically “generating” or “printing” lots and lots of pages. That’s where today customers are going to Next.js instead of Gatsby.
Drew: One of the problems that everyone seems to run into as their JavaScript-based solution gets bigger is performance and how things can start getting pretty slow, you have big bundle sizes. Traditionally, things like code splitting can be fairly complex to get configured correctly. I see that’s one of the features that jumped out at me of Next.js, that it claims that the code splitting is automatic. What does Next.js do in terms of code splitting to make that work?
Guillermo: Your observation is 100% right. One of the biggest things with the web and one of the biggest weights on the web is JavaScript, and just like different materials have different densities and weights irrespective of the actual physical volume, JavaScript tends to be a very dense, heavy element. Even small amounts of JavaScript compared to, like for example, images that can be processed asynchronously and off the main thread, JavaScript tends to be particularly bothersome.
Guillermo: Next.js has invested a tremendous amount of effort into automatically optimizing your bundles. The first one that was my first intuition when I first came up with the idea for Next.js was you’re going to define, for example, 10 routes. In the Next.js world you create a pages directory and you drop your files in there Index.js, About.js, Settings.js, Dashboard.js, Termsofservice.js, Signup.js, Login.js. Those become entry points to your application that you can share through all kinds of media.
Guillermo: When you enter those, we want to give you JS that is relevant for that page first and foremost, and then perhaps a common bundle so that subsequent navigations within the system are very snappy. Next.js also, which is very, very nice, automatically pre-fetches the rest of the pages that are connected to that entry point, such that it feels like a single-page application. A lot of people say like, “Why not just use Create React app if I know that I have maybe a couple routes?” I always tell them, “Look, you can find those as pages, and because Next.js will automatically pre-fetch ones that are connected, you end up getting your single-page application, but it’s better optimized with regards to that initial paint, that initial entry point.”
Guillermo: That was the initial code splitting approach, but then it became a lot more sophisticated over time. Google contributed a very nice optimization called Module and No Module, which will give differential JS to modern browsers, and legacy JS that’s heavy with polyfields to other browsers, and this optimization 100% automated and produces massive savings. We gave it to one of our customers that we host on Vercel called Parnaby’s, I believe if I’m not mistaken, it was something very, very significant. It was maybe like 30% savings in code sizes, and that was just because they upgraded Next.js to a version that optimized JS bundles better.
Guillermo: That was kind of the point that we were going over earlier, which is you choose Next.js and it only gets better and more optimal over time, it’ll continue to optimize things on your behalf. Those are, again, pre-configurations that you would never have to deal with or be bothered with, and the research of which you don’t ever even want to do, to be honest. Like I wasn’t obviously very involved with this, but I look at some of the internal discussions and they were discussing all these polyfields that only mattered to Internet Explorer X and Soho, I was like, “I don’t even want to know, let’s just upgrade Next.js and get all these benefits.”
Drew: There is sometimes great benefits on there with sticking with the defaults and sticking with the most common configuration of things, which seems to be really the Next.js approach. I remember when I started writing PHP back in the early 2000s, and everybody was using PHP and MySQL, and at the time I’d just come from Windows so I wanted to use PHP and Microsoft Sequel Server. You can do it, but you’re swimming against the tide the whole way. Then as soon as I just switched over to MySQL, the whole ecosystem just started working for me and I didn’t need to think about it.
Guillermo: Yeah, everything just clicks, that is such a great observation. We see that all the time, like the Babel ecosystem is so powerful now that you could become, for example, a little bit faster by swapping Babel for something else, but then you trade off that incredible ecosystem compatibility. This is something you touched on performance earlier, and like for a lot of people, build performance and static generation performance is a big bottleneck, and this is something that we are very diligent in improving the performance of our tools incrementally.
Guillermo: For example, one of the things that Next.js is doing now is that it’s upgrading its default from Webpack 4 to Webpack 5, which has some breaking things, and that’s why we’re first offering it to people as an opt-in flag, but later on it’ll become the default. Webpack 5 makes incredible performance improvements, but we’re not sacrificing the Webpack ecosystem, we incrementally improved. Sure, there were some very small things that needed to be sacrificed, but that’s an incredible benefit of the JS ecosystem today that a lot of people are glossing over, I think, because maybe they see, “Oh, we could’ve done X in Soho, maybe it was a little faster, or maybe MPM in Soho would take less time.” They pick up some details and they miss the bigger picture, which is the ecosystem value is enormous.
Drew: The value of having all the configuration and the maintenance and that side of it done by a project like Next.js rather than taking that on yourself by swapping to using something else is incredible, because as soon as you move away from those defaults, you’re taking on the burden of keeping all the compatibilities going and doing it yourself. One of the things that I’ve been really interested in with Next.js is there are options available for either doing static site generation or server-side rendering, or maybe a hybrid of the two perhaps. I think there’s been some recent changes to this in a recent update, can you tell us a little bit about that and when you might choose one or the other?
Guillermo: Yeah, for sure. One of the key components of this hybrid approach combined with the page system that I described earlier is that you can have pages that are fully static or pages that server rendered. A page that’s fully static has the incredible benefit of what I call static hoisting, which is you can take that asset and automatically put it at the edge. By putting it at the edge, I mean you can cache it, you can preemptively cache it, you can replicate it, you can make it so that when a request comes in, it never touches the server because we know ahead of time, “Hey, Slash Index is a static.”
Guillermo: That’s a very, very interesting benefit when it comes down to serving global audiences. You basically get an automatic CDN out of the box, especially when you deploy the modern edge networks like Vercel or AWS Amplify or Netlify and so on. Next.js has this premise of if it can be made static, it should be static. When you’re first starting a project and you’re working on your first page or you’re kicking the tires of the framework, might as well make everything static.
Guillermo: Even for high end needs, so for example, vercel.com, our own usage of Next.js is fully static. It’s a combination of fully static and static site generation, so all our marketing agency pages are static, our blog is statically generated from a dynamic data source, and then our dashboard which has lots of dynamic data, but we can deliver it as shells or skeletons, all the pages associated with viewing your deployments, viewing your projects, viewing your logs, et cetera, et cetera, are all basically static pages with client-side JavaScript.
Guillermo: That serves us incredibly well because everything where we need a very fast first-pane performance is already pre-rendered, everything that needs SEO Company, already pre-rendered, and everything that’s extremely dynamic, we only have to worry about security, for example, from the perspective of the client side which uses the same API calls that, for example, our CLI used or our integrations use, et cetera, et cetera. A fully static website, very cheap to operate, incredibly scalable and so on and so forth.
Guillermo: Now, one particular thing that we needed with our blog was we wanted to update the data very quickly. We wanted to fix a typo very quickly and not wait for an entire build to happen, and this is a very significant benefit of Next.js, that as you straddle from a static to a dynamic, it gives you these in between solutions as well. For our blog we used incremental static generation, so essentially we can rebuild one page at a time when the underlying content changes.
Guillermo: Imagine that we had not just a couple hundred blog posts and we had lots of blog posts being generated all the time and being updated all the time, like I mentioned one of our customers, Washington Post, in that case you need to go more toward full SSR, especially as you start customizing the content for each user. That journey of complexity that I just described started from I have one marketing agency page, to I have a blog that has a couple thousand pages, to I have tens of thousands or millions of pages. That’s the Next.js journey that you can traverse with your own business.
Guillermo: Then you start as a developer to choose between perhaps less responsibility to more responsibility, because when you opt in to using SSR, you’re now executing code on the server, you’re executing code on the cloud, there’s more responsibility with more power. The fact that you can decide where you use each kind of tool is I think a very, very interesting benefit of Next.
Drew: Just in practicalities of combining the static site generation and the server-side rendering, how does that work in terms of the server element? Are you needing a dedicated platform like Vercel to be able to achieve that, or is that something that can be done more straightforwardly and more simply?
Guillermo: Next.js gives you a dev server, so you download Next and you run your Next Dev, and that’s the dev server. The dev server is obviously incredibly optimized for development, like it has the latest fast refresh technology that Facebook released, where … Actually, Facebook didn’t release it, Facebook uses it internally to get the best and most performant and most reliable hot module replacement, such that you’re basically typing and it changes are reflecting on the screen, so that’s the dev server.
Guillermo: Then Next gives you a production server called Next Start, and Next Start has all the capabilities of the framework for self-hosting. The interesting thing about Vercel is that when you deploy Next to it, it gets automatically optimized and it’s 100% serverless, meaning there’s no responsibility whatsoever of administration, scaling, cashing and cashing validation, purging, replication, global fail over and so on and so forth that you would have to take on when you run Next Start yourself.
Guillermo: That’s also the great benefit of Next.js, so for example, apple.com has several different properties, subdomains and pages on dotcom on Next.js they self-host, due to very, very advanced and stringent security and privacy needs. On the other hand, washingtonpost.com uses Vercel, so we have this sort of wide range of users, and we’re extremely happy to support all of them. The nice thing about where serverless is headed in my opinion is it can give you best of both worlds in terms of the most optimal performance that only gets better over time, with the best developer experience of like, “Hey, I don’t have to worry about any sort of infrastructure.”
Drew: The Next.js is an open source project that’s being developed by the team at Vercel. Are there other contributors outside of Vercel?
Guillermo: Yeah, so Google Chrome being the main one that actively submit server PRs, help us with optimizations and testing it with partners, like very large Next.js users that are already part of the Google ecosystem, for example, due to using lots and lots of apps, so they need to be involved closely as partners. Facebook, we maintain a great relationship with the Facebook team. For example, fast refresh, we were the first React framework to land that, and they helped guide us through all the things that they learned of using React and fast refresh at Facebook.
Guillermo: We work with lots of partners that have very large deployments of Next.js apps in the wild from all kinds of different sort of use cases, like imagine e-commerce and content. Then there’s just lots and lots of independent contributors, people that use Next.js personally, but also educators and members of front infrastructure teams at large companies. It’s a very, very wide community effort.
Drew: It sounds like the concern that somebody might have, that this is being developed in a significant part by Vercel, that they might have the concern that they’re going to get sort of locked into deploying on that particular platform, but it sounds very much like that’s not the case at all, and they could develop a site and deploy it on Firebase or Netlify or…
Guillermo: Yeah, absolutely. I like to compare it a lot for like the Kubernetes of the Front End age in a way, because at the end of the day I am a firm believer that … Kubernetes is something that pretty much almost everyone needs when they need to run LinUX processes, like you were talking about opinionation and you’re saying it’s a good technology, it’s very much not opinionated, but there is some opinionation that we kind of forget about. It’s like at the end of the day, it grew out of running a specific demons of LinUX programs packaged as containers.
Guillermo: Next is in a similar position, because what we take for being the universal primitive of the world as a React component, obviously it’s opinionated, but we do think that for lots of enterprises, just like they all gravitate towards LinUX, we are seeing the same thing towards React and Vue, but Vue luckily has NUXt too, which is a very awesome solution, it’s equivalent in ideation and principles as Next. We’re gravitating towards these platforms like Next.js, like NUXt, like Sapper for the Svelte ecosystem.
Guillermo: I think these should be open platforms, because again, if everybody’s going to need this, might as well not reinvent the wheel across the entire industry, right? We very much welcome that position, we welcome people to deploy it and reconfigure it and rebuild it and redistribute it and so on.
Drew: Just recently a new version of Next.js was released, I think version 9.5. What significant changes were there in that release?
Guillermo: The most awesome one is, as I was saying earlier, a lot of things start static and then become more dynamic as things grow. This was the venture for WordPress, by the way. WordPress in the beginning was based on a static file database approach, and then grew into needing a database, kind of like what you described with how PHP evolved to be more and more MySQL. What’s nice about Next.js 9.5 is that it makes incremental static generation a production ready feature, so we took it out of the unstable flag.
Guillermo: This feature allows you to make that journey from static to dynamic without giving up on all the static benefits, and without having to go full for server-rendered dynamic, so it stretches the useful lifetime of your sort of static. The way we use it at Vercel, for example, as I mentioned, it’s like our blog gets fully pre-rendered at build time, but then for example, we’re actually in a couple minutes about to make a major announcement, and when we blog about it we want to be able to tweak it, fix it, preview it, et cetera without having to issue a five to 10-minute build every time we change one letter of one blog post.
Guillermo: With incremental static generation, you can rebuild one page at a time. What could take minutes or even seconds, depending on how big your site is, now takes milliseconds. Again, you didn’t have to give up on any of the benefits of static. That’s perhaps the thing I’m most excited about that went stable on Next.js 9.5, and specifically because the JS community and the React community and the framework community and static site generated community have been talking about this unicorn of making a static incremental for a long time, so the fact that Next.js did it, it’s being used in production and it’s there for everybody to use, I think it’s a major, major, major milestone.
Guillermo: There’s lots of little DX benefits. One that’s really nice in my opinion is Next.js, as I said, has a page system. You would argue, “Okay, so let’s say that I’m uber.com and I’ve decided to migrate on Next.js, do I need to migrate every URL inside over to Next.js in order to go live?” This has become a pretty important concern for us, because lots of people choose Next.js, but they already are running big things, so how do you reconcile the two?
Guillermo: One of the things that Next.js allows you to do in 9.5 is you can say, “I want to handle all new pages that I created with Next.js with Next.js, and the rest I want to hand off to a legacy system.” That allows you incremental, incremental is the keyword here today, incremental adoption of Next.js. You can sort of begin to strangle your legacy application with your Next.js optimized application one page at a time, when you deploy and you introduce in your Next.js page, it gets handled by Next. If it doesn’t match the Next.js routing system, it goes to the legacy system.
Drew: That sounds incredibly powerful, and the incremental rendering piece of that, I can think of several projects immediately that would really benefit that have maybe 30-minute build times for fixing a typo, as you say. That sort of technology is a big change.
Guillermo: We talked to one of the largest, I believe, use cases in Jamstack in the wild, and it was basically a documentation website and their build times were 40 minutes. We’re doing a lot in this space, by the way, like we’re making pre-rendering a lot faster as well. One of my intuitions for years to come is that as platforms get better, as the primitives get better, as the build pipelines get better we’re going to continue to extend the useful lifetime of statics. Like what ended up taking 40 minutes is going to take four.
Guillermo: A great example is we’re rolling out an incremental build cache, as well, system. I sort of pre-announced it on Twitter the other day, we’re already seeing 5.5 times faster incremental builds. One of the things that I like about Jamstack is that the core tenet is pre-render as much as possible. I do think that’s extremely valuable, because when you’re pre-rendering you’re not rendering just in time at runtime. Like what otherwise the visitor would incur in in terms of rendering costs on the server gets transferred to build time.
Guillermo: One of the most exciting things that’s coming to Next is that without you doing anything as well, the build process is also getting faster. On the Vercel side, we’re also taking advantage of some new cloud technology to make pre-rendering a lot faster as well. I think we’re always going to live in this hybrid world, but as technology gets better, build times will get better, pre-rendering will get better and faster, and then you’ll have more and more opportunities to do kind of a mix of the two.
Drew: Sounds like there’s some really exciting things coming in the future for Next.js. Is there anything else we should know before we sort of go away and get started working with Next.js?
Guillermo: Yeah. I think for a lot of people for whom this is new, you can go to nextjs.org/learn, it’ll walk you through building your first small static site with Next.js, and then it’ll walk you through the journey of adding more and more complexity over time, so it��s a really fun tutorial. I recommend also staying tuned for our announcement that I was just starting to share on twitter.com/vercel, where we share a lot of Next.js news. Specifically we highlight a lot of the work that’s being done on our open source projects and our community projects and so on. For myself as well, twitter.com/rauchg if you want to stay on top of our thoughts on the ecosystem.
Drew: I’ve been learning all about Next.js today, what have you been learning about lately, Guillermo?
Guillermo: As a random tangent that I’ve been learning about, I decided to study more economics, so I’ve been really concerned with like what is the next big thing that’s coming in terms of enabling people at scale to live better lives. I think we’re going through a transition period, especially in the US, of noticing that a lot of the institutions that people were “banking on”, like the education system, like the healthcare system, a lot of those, like where you live and whether you’re going to own a house or rent and things like that, a lot of these things are changing, they have changed rapidly, and people have lost their compass.
Guillermo: Things like, “Oh, should I go to college? Should I get a student loan?” and things like that, and there is a case to be made for capitalism 3.0, and there is a case to be made for next level of evolution in social and economic systems. I’ve been just trying to expand my horizons in learning a lot more about what could be next, no pun intended. I’ve found there’s lots of great materials and lots of great books. A lot of people have been thinking about this problem, and there is lots of interesting solutions in the making.
Drew: That’s fascinating. If you, dear listener, would like to hear more from Guillermo, you can find him on Twitter at @RauchG, and you can find more about Next.js and keep up to date with everything that goes on in that space at nextjs.org. Thanks for joining us today, Guillermo. Do you have any parting words?
Guillermo: No, thank you for having me.
(il)
Website Design & SEO Delray Beach by DBL07.co
Delray Beach SEO
source http://www.scpie.org/smashing-podcast-episode-23-with-guillermo-rauch-what-is-next-js/
0 notes
waiozseo · 6 years ago
Text
What JavaScript Framework Should you Choose for Your Website
Emerging trends in front end design of various websites across the internet portal directly correlates with escalating use of JavaScript framework. Having become popular amongst the front end developers, the frameworks which run JavaScript have scaled to new heights. With a much enhanced JavaScript development environment for frontend developers, the new age frameworks provide one other dilemma.  
 Which JavaScript Framework Provides the ideal Platform to Perform the Tasks Effectively?
 The answer to this question is subjective to the requirements that govern the project. Each framework has its own distinctive features that might sway your decision in choosing that particular framework. Some frameworks are well documented, while few others have a strong support community and some are quite easy to integrate and implement in your project.  
 This article will do you a favor by weighing up the pros and cons of each JS framework. Making it easy for frontend developers to choose the right JavaScript’s framework that governs their web application development. 
 AngularJS
 AngularJS is one of the most common, yet dominant JavaScript Framework, which is also highly regarded for its effectiveness in client-side development. The robustness of the framework is an ideal fit for the requirements of small and mid-level industries, often referred to as Model View Whatever framework. With React JS releasing for the masses, the older angular version faced a stiff competition from it, losing a bit of popularity. However, with the release of Angular 5 and Angular 6, it has become popular again among the frontend developers.
 The new released versions have reinforced its foothold with myriad of new features that compliment frontend mobile and web development. Introduced to make JavaScript more accessible and agile among the users and developers alike, AngularJS is still regarded as the best JS framework to build Single Page Applications. 
 Reasons to Prefer AngularJS over other Frameworks
·         DOM manipulation
·         Two-Way Data Binding Ability
·         Extensive features that are well tested 
·         Google assisted and aided
·         Strong and staunch following community
·         Material UI integration improved by PWAs and optimizer 
 ReactJS
 Developed by Facebook, React was initially used internally for its news feed. The effectiveness of react was realized when it was open sourced in 2013. The effectiveness in creating single page applications, SPAs was complemented with ability to create UI components that are both interactive and reusable.
 The main advantage of react is that it seamlessly integrates with any development architecture, facilitating both the client and server side rendering, making simultaneous working possible. The rendering of sub-trees of nodes that changes is also supported in react with a use of a virtual DOM. The node changes can be depicted by writing codes as if the each page gets rendered upon when such node changes occur.
 It also boasts an extension to the JS language syntax called the JSX that helps in structuring each render with familiar code syntax. The handling of APIs and DOMs are simplified and allow changes to be done in HTML and XML documents. 
 Reasons to Prefer ReactJS over other Frameworks
·         Offers a smooth learning curve
·         Fits on other frameworks as a view only layer
·         Performance is improved with the help of virtual DOM
·         Enables re-usability of components  
·         Code stabilized with unidirectional data flow
·         Open-source library
 Vue.js
 In many ways Vue.js is quite similar to ReactJS framework. Vue.js also boasts a virtual DOM to enhance the performance. Like ReactJS, Vue.js is also a framework for view layer. Vue.js, like react, also requires the storage of component logic and its layout that are apart from the style sheet in one single file. The use props and state objects also adds to the similarity of Vue with React.
However, an in-depth analysis would reveal that it is a combination of AngularJS and ReactJS. The market aim of Vue was in itself blending the features of React and Angular frameworks. Like Angular, Vue.js also mixes JavaScript with HTML, while the developers on Vue also have got to use v-bind values in templates. 
Working on Vue can be particular tricky if you haven’t used AngularJS or ReactJS. With a reasonable level of understanding of Angular and React, one can really make use of Vue.js to a good effect. The presence of a Redux library which makes it easy to develop complex large applications.  
Reasons to Prefer Vue.js over other Frameworks
·         The size of Vue.js is much smaller
·         With the knowledge of Angular and React, it is much simpler to use. 
·         Easy integration
·         Well documented
·         Extremely flexible
·         Allows a two way communication between server and client
There are a few other JavaScript frameworks like EmberJS, NextJS and BackboneJS which are slowing hitting the prominence. However, the forefront of JavaScript framework is still occupied by AngularJS, ReactJS and Vue.js. Each of the frameworks has its unique advantages over the other in terms of simplicity, usability and problem solving ability. 
 If you are looking to have your website built up to effect, seek out for a professional JavaScript Development company. Feel free to contact us to have a doubts on JavaScript clarified. 
0 notes
tak4hir0 · 6 years ago
Link
In an attempt to dispel the idea that if you have to google stuff you’re not a proper engineer, this is a list of nearly everything I googled in a week at work, where I’m a software engineer with several years’ experience. Obviously these weren’t all googled in a row (although you can probably spot that a few were), but throughout the day. I can’t remember the context of everything I was googling, but hopefully it’ll make you feel a little better next time you have to google something. Mondaynpm react-testing-library - during a React upgrade, looking at dependencies to see latest versions and checking for breaking changes. Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a "gql" tag? - said React upgrade then started causing some super fun errors. react-apollo release notes react-apollo/test-utils - tests were throwing some odd errors with our graphQL components. undo a rebase - oops. react testing library apollo "invariant violation" - package upgrades are so much fun! jest silence warnings - don’t judge me, ok? semantic HTML contact details - wanted to check if the tag was relevant here aa contrast checker temporary visual impairment - fact checking for an accessibility talk I was giving that week dominos accessibility - popcorn.gif shame gif - an important part of any presentation Tuesdayjavascript get array of unique dates - if I have an array of Dates, how can I filter them so they are unique? (reduce, naturally, but I can rarely use that without googling it first) date to locale string js date to locale string - after I got a load of Java results alternatives to Moment.js - it’s large group array items by date - more reduce fun sort object keys javascript react fragment keys next link - needed a reminder of how to use the Link component in Next.JS React.Children.only expected to receive a single React element child. visual studio code disable autocomplete html - it keeps autoclosing HTML elements on the same line, and I still can’t switch it off dt dd dl - couldn’t remember what the example use for these was. html nested sections - is it ok to have inside ? display dl in pairs veggie ipsum - the best lorem ipsum generator css keyframes css animate underline text dl vs ul react generating keys - should I use some kind of hash, or should I use data in the props? (I ended up constructing a string with unique timestamp data) css checkbox - can we style checkboxes yet? (no) flexbox center span - it was 17:24 and I was tired by this point grid minmax flexible grid row - I don’t have a whole lot of CSS Grid experience, so I always end up googling a ton with this. grid row height auto cauliflower shortage - someone told me about this and I panicked next.js hooks - we can use them, right? (we can, and I did) Wednesdaycors - today is going to be bleak the corrs - once I hit some CORS errors I decided I needed to make a meme, and I needed to find the perfect image. It took a surprisingly long time. Worth itgit patch trailing whitespace - I was sent a git patch with some whitespace that prevented it from actually patching jsx annotation web api fetch preflight - in my CORS adventures I wanted to read up a bit more about preflight requests. web api fetch origin header discriminated union flow - trying to diagnose problems with my Flow types. whitespace regex - is it \w? (no, that’s a word - it’s \s) regex not letter pat butcher emoji - what can I say, I google important things woman shouting at cat google oauth next.js authentication - sometimes it’s helpful to google stuff to see if anyone has written examples of how to do common flows in the framework or tool that you’re using component displayname - do I need to do this with my higher-order components? nextCookie - starting to mess around with oauth cookies reading cookies in react - there must be a better way than document.cookie js-cookie npm cookies-js npm cookie universal-cookie google oauth cookie 🍪 Thursday"log in with google" localhost - was having all sorts of problems getting this to work httpserverrequest javascript - I have a feeling this was something to do with Flow types nextjs flowtypes - yep, there you go "python-social-auth" react - trying to figure out if the django backend I was working with would play nicely with my React frontend google social login vary header get cookie from 302 google social login cookies - I was having a really fun time with this as you can tell google oauth cookie python-social-auth set-cookie python-social-auth site:stackoverflow.com python-social-auth react site:stackoverflow.com django - I think I gave up at this point and just googled Django because I have literally never used it fetch send cookies testing same origin credentials locally cross origin cookies - spoiler alert: not a thing useState default value "The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when when the request's credentials mode is 'include'. - googling error messages is only second to console.log() as a debugging method useState with empty array react hooks initial state empty array "Provisional headers are shown" - this is where the requests weren’t going through and I couldn’t see what the actual headers being sent were fetch send cookies how to see request headers in chrome fetch not sending cookies Thursday was a whole lot of fun D: Fridayprovisional headers are shown - still at it. sending cookies from localhost - have I mentioned that I hate cookies? editing host file - desperate times (and it didn’t even work) sending cookies with different domain next cookie getinitialprops functional component getting cookies from document js find - to check the usage and return types string contains string methods js - I can’t keep any of these in my head js string methods - 20 mins later js fetch manual cookie django react cookies localhost django react cookies localhost site:stackoverflow.com httponly cookie django httponly async await promise.all nextjs port google appengine node ports next rename static install gcloud cli method patch - couldn’t remember what the HTTP method PATCH does. nextjs env next.js environment variables next js docs editing data with hooks - literally no idea what I was trying to google here but this was past 5pm so I was evidently quite tired react form submit dayjs - I needed the documentation again. What I’m trying to show with all this is that you can do something 100 times but still not remember how to do it off the top of your head. Never be ashamed of googling, even if it seems like the most basic thing you’re looking up. I can never remember how Date works. I’ve built plenty of forms in React but couldn’t remember how onSubmit worked on the Friday evening at 5:30pm. I constantly have to google JS string methods. Cookies are terrible. (Incidentally, we fixed the cookie issue by running everything in a docker container and tunneling with ngrok, so everything’s on the same domain.)
0 notes
tandem-nz-blog · 6 years ago
Text
Top 8 Advantages of using ReactJS
The front-end ecosystem is constantly evolving and changing. The past few years have witnessed a massive growth in modern web and mobile applications. Powered by lightweight and sophisticated JavaScript libraries.
React is a JavaScript library used for building a user interface. It can be easily labeled as a best seller. This JavaScript was launched back in 2013.
Today ReactJS is maintained by Facebook, together with the developer community. React JS has achieved massive popularity because of its great looking user interfaces (UI).  
In React JS, HTML and JavaScript are bound to collaborate side by side, it leverages faster web page load speed, it is SEO friendly and it also offers code re-usability by combining the two technologies.
The reason behind the popularity of React JS is its simplicity. Businesses were quick to grasp this technology. With ReactJS, it is easy to reap the benefits of code re-usability with hassle-free addition/modification of functionalities in the existing system.
Many companies at the top of their fields have identified the benefits of ReactJS in their business. The list of companies utilizing React in production include heavy weights like Facebook, Instagram, Netflix, Whatsapp, Salesforce, Uber, The New York Times, CNN,
Dropbox, DailyMotion, IMDB, Venmo, Paypal and Reddit, besides hundreds of other medium to large scale companies. To understand why business is converging towards the ReactJS, we need to know its primary features. Features that facilitate the creation of high performance and agile applications. In this article, we’ll cover all the advantages of using React JS.
8 Major advantage of using ReactJS
It facilitates the overall process of writing components
It boosts productivity and facilitates further maintenance
It ensures faster rendering
It guarantees stable code
SEO friendly
It comes with a helpful developer toolset
There is React Native for mobile app development
It is backed by a strong community
It facilitates the overall process of writing components
JavaScript has an optional syntax extension called JSX. JSX makes writing your own components much easier. It quotes HTML and makes a sub component rendering easier.  In fact, it is a set of shortcuts for writing React. You can create elements with a few rules to make your source cleaner and simpler.
JSX has proven its benefits in building up of high-volume apps or custom components, excluding typos in large tree structures, and making it easier to convert from HTML mockups to ReactElement trees. Besides that, JSX provides information, warning and error message to React developers and it also helps to prevent code injections.
It boosts productivity and facilitates further maintenance
Often, updates turn into a headache because change in one component of the application can affect other components.
Just to solve this issue React was supplemented with the ability to reuse system components. Experts define this new component as one of the best features of React JS.
Designers appreciate the feature re-use, as it helps them to typically reemploy the same digital objects. Re-use ensures consistent app look and facilitates code base maintenance and growth.
It ensures faster rendering
Before building any high load application, it is essential to consider how the structure will impact the overall app performance.
To resolve this issue Facebook development team has introduced a Virtual Document Object Model (DOM). This is one the benefit of using React for heavy loaded and dynamic software solution.
As the name suggests “Virtual”, it is the virtual representation of the document object model, so all the changes are applied to the virtual DOM first and then, using the diff algorithm, the minimal scope of necessary DOM operations is calculated, later the real DOM tree is updated. The updation of the real DOM tree is to ensure that minimum time is consumed while rendering. This method guarantees a better user experience and higher app performance.
It guarantees stable code
ReactJS makes sure that the small changes taking place in the child structures won’t affect their parents, that’s why it uses only downward data flow. To ensure code stability in changing an object, developers just modify its state, make changes, and, after that, only particular components will be updated, this also ensures continuous app performance.
SEO friendly
ReactJS has the ability to deal with a common search engine failure to read JavaScript-heavy apps. To do this, React run on the server, rendering and returning the virtual DOM to the browser as a regular web page.
It comes with a helpful developer toolset
One of the important advantages of ReactJS is its coverage with debugging and design tools. ��React Developer Tools is a browser extension which is available for both the Chrome and Firefox. This browser extension enables developers to find the child and parent components, it helps to observe reactive component hierarchies and  inspect their current state and props.
There is React Native for mobile app development
React follows same design pattern and it facilitates the same transition process on the web and mobile application development. You can build a rich UI for native apps supported by both iOS and Android platforms with plain JavaScript and React .
Some other advantages of ReachJS in mobile app development are its portability and ability to reuse components ,real-time reload and modular architecture,supported by an open source, and generous ecosystem.
It is backed by a strong community
Currently, the React library is supported by Facebook and Instagram engineering teams, along with some external experts and users can ask their questions on Stack Overflow, Discussion forum, Reactiflux Chart, Freenode IRC, social media platforms and many others.
At Tandem NZ, we have a well-qualified team of JavaScript experts. We are React core contributors, open source supporters, and creative thinkers. We believe in contributing towards improving the modern web. One of the ways we use to push your business forward is through our excellent ReactJS, NodeJS, NextJS, RedUX, and Reactive Native services. To avail these services please contact us now.
0 notes