Best Practices & Beyond in Next.js

Next JS has become a prominent framework recently in building server-rendered React applications. It empowers you to build web applications that load instantly, keep users engaged, and thrive under heavy traffic. To obtain it, mastering Next JS best practices is the key. The characteristics of this framework, like simplicity, server-side rendering support, file-based routing, and good developer experience, made it the first choice of developers in building high-performance web applications.

With the rapid growth, identifying the best practices of Next JS is important for developers to ensure that they are building applications with optimized performance, maintainability, and scalability. This article will be a guide to discovering the best practices of Next JS that harness their full potential.

Whether you’re a beginner or an experienced developer, following these best practices is valuable for writing cleaner and more efficient code and delivering the best user experience. Therefore, let’s dig deeper into the topic.

Setting up the VS Code

First things first, you need to set up your VS Code (for all the non-geeks, VS code is where the developers code, much like a text editor, but for coding). Well, obviously, I'm not gonna tell you to download and install it. But what I want you to do is use Absolute Paths. Let me tell you why. It will let you move your components without editing a lot of code, and it will also let you see where each file originates.

Use Absolute Paths

Flexibility is the key to your project's structure. Therefore, using absolute paths lets you move components without editing a lot of code. You can also easily see where each file originates. Through below code snippet below, you can see how to use absolute paths in the installation.

// Relative paths
import Input from '../../../modules/common/components/Input'

// Absolute paths
import Input from '@modules/common/components/Input'

The tsconfig.json file will look like this

"baseUrl": "./app",
"paths": {
	"@components/*": ["./components/*"],
	"@assets/*": ["./assets/*"],
    "@hooks/*": ["./hooks/*"],
    "@styles/*": ["./styles/*"],
    "@service/*": ["./service/*"],
    "@constants/*": ["./utils/constants/*"],
    "@helpers/*": ["./utils/helpers/*"],
    "@type/*": ["./utils/types/*"]
}

Next Js Folder Structure

The second important part is maintaining the Next JS folder structure. Better file organization will help you maintain the project easily without wasting time. In your project, organize React components into folders for each module. New components are stored in their respective module folders. Using an index.js file in each component folder simplifies imports and avoids repetition. You can import components as import Input from 'components/Input' instead of lengthy paths. Remember to keep the component file named for clarity when working with multiple files.

App Directory Structure

For a better app directory structure, please maintain different components as below.

  • Page component name: [ page.tsx = Page + (Name) ]
  • Layout component name: [ layout.tsx = Layout + Name ]
  • View component name: [ View.tsx = View + (Name) ]

The below image illustrates more about folder structure maintenance.

--> App
   --> View				--> client component
   --> (sub component)
   ├── View.tsx 		
   ├── page.module.scss
   ├── layout.tsx
   ├── page.tsx 		--> server component
--> components
--> hooks
--> service
--> styles
--> utils

The below instances preview how different folder structures can be maintained.

Styles Folder

--> styles
 	├── globals.css
 	├── colors.module.scss
	├── (custom resuable file).module.scss
	├── (third party libraries).css

Components Folder

--> components
   --> providers
      --> (sub folder) 					--> Provider Name	
         ├── index.ts (optional)		-- export
         ├── context.ts				   -- default export
         ├── Provider.tsx				-- default export
   --> (resuable components)

A Reusable Component structure (Following MUI Folder Approach)

--> components
   --> icons
      ├── Icon.ts 		--> Icon type file 		-- default export
      --> Logo
         ├── (file).svg
         ├── (File).tsx	--> Icon + Name	-- default export
         ├── index.ts (optional)			-- export
   --> inputs
      --> Button
      --> TextField
   --> navigation
      --> Layout
      --> Drawer
   --> surface
      --> cards
      --> Loader

A Component includes these files

--> Header
  	├── (sub folder)
   	├── index.ts	(optional)					-- export
   	├── Header.tsx						-- default export
   	├── element.module.scss
   	├── Header.test.tsx (optional)

Service Folder

Service folder classified into server (contains server related functions) and client (contains client related functions)

--> service
   --> client
      --> (sub folder)
            ├── (functions).ts 				-- default export
            ├── index.ts					-- export
         ├── (functions).ts 					-- default export
         ├── index.ts						-- export
   --> server
      --> (sub folder)
         ├── (functions).ts 				-- default export
         ├── index.ts

Hooks Folder

--> hooks
	├── use(name).ts 					-- default export
	├── index.ts

Utils Folder

--> utils
   --> helpers
      ├── (functions).ts					-- default export
      ├── index.ts						-- export
   --> enum
      ├── (strings).ts					-- default export
      ├── index.ts						-- export
   --> types
      --> (sub folders)
      ├── (interface).interface.ts 			-- default export
      ├── (type).ts 					-- default export
      ├── index.ts

Install Prettier

Prettier is an opinionated code framework that helps maintain consistent coding styles in your projects. In the context of following Next JS best practices, using VS code with Prettier helps maintain a clean, consistent, and more readable codebase that aligns with the project’s formatting styles. This is beneficial in collaborative projects to maintain multiple code contributions from developers. By installing Prettier, all developers can use one consistently formatted codebase throughout the company. Follow the link for more information on Prettier: https://prettier.io/

yarn add --dev --exact prettier

folder root -> .vscode folder -> settings.json
{
   	"editor.defaultFormatter": "esbenp.prettier-vscode",
   	"editor.formatOnSave": true
}

Configuration

This guide provides you with the path on Prettier configuration as well.

For that create a file called .prettierrc in the root directory and add this. Install @IanVS/prettier-plugin-sort-imports

First, Create a file called .prettierrc in the root directory. Add this Install @IanVS/prettier-plugin-sort-imports

{
   	"trailingComma": "es5",
   	"tabWidth": 2,
   	"semi": true,
   	"singleQuote": true,
   	"printWidth": 100,
	"plugins": ["@ianvs/prettier-plugin-sort-imports"],
	"importOrder": [
		 "^(next/(.*)$)|^(next$)",
		 "^(react/(.*)$)|^(react$)",
		 ">THIRD_PARTY_MODULES<",
		 "^types$",
		 "^@hooks/(.*)$",
		 "^@service/(.*)$",
		 "^@type/(.*)$",
		 "^@constants/(.*)$",
		 "^@components/(.*)$",
		 "^@assets/(.*)$",
		 "^@/app/(.*)$",
		 "^@styles/(.*)$",
		 "^(?!.*[.]scss$)[./].*$",
		 ".scss$"
	   ]
}

Git Ignore

After that, it’s time for the Git Ignore command to specify the intentionally untracked files.

There, create a file called .prettierignore in the root directory and add this.

.npm
.yarn
.next
dist
node_modules 

Install Husky

Another important installation is Husky. It makes managing Git hooks in JavaScript projects a breeze. These hooks are scripts that run automatically at certain points in the Git workflow, like before committing or pushing changes. Follow the link for more information: https://typicode.github.io/husky/

In Next.js projects, Husky helps enforce code quality and consistency by running checks before commits are allowed. This catches potential issues early on, saving development time and reducing headaches.

Here is the flow to install Husky.

// To install husky
yarn add --dev husky

// To create a hook run
npx husky init

// To change pre-commit to yarn build
echo "yarn build" > .husky/pre-commit
// Update package.json
"scripts: {
      ...
      "prepare": "husky || true"
} 

In conclusion, this guide has ended, and now it’s your chance to use its best practices in your coding. Apply these best practices to your Next JS projects and see the potential of their usage. Also, this doesn’t stop here. With the evolution there will be best practices come in way in the future. So stay curious and explore more.

Happy Coding!

Next Article - Level Up Your Web Styling

Written by Development Team
CODIMITE
"CODIMITE" Would Like To Send You Notifications
Our notifications keep you updated with the latest articles and news. Would you like to receive these notifications and stay connected ?
Not Now
Yes Please