Every web project reaches a moment where pages start growing. What began as a simple layout suddenly needs navigation for dashboards, settings, reports, and users.
This is where sidebars quietly become one of the most important parts of an application.
Whether you’re building a SaaS product, an internal admin tool, or a client dashboard, a good sidebar helps users move around without thinking. A bad one, on the other hand, slows everyone down. This article is written for developers who want to avoid that mistake and pick the right Bootstrap sidebar from the start.
What You’ll Learn From This Article
In this guide, you’ll learn:
Why sidebars matter in real-world Bootstrap projects
The difference between dashboard-ready sidebars and simple code snippets
Which open source Bootstrap sidebars work best for SaaS, admin panels, and internal tools
How responsiveness, navigation structure, and customization affect usability
When to choose a full template and when a lightweight sidebar example is enough
By the end, you should have a clear idea of which sidebar fits your project and why.
Why Sidebars Are Important in Bootstrap Projects
Sidebars do more than hold links. They define how users explore your application.
In dashboards and SaaS apps, sidebars usually stay visible, giving quick access to important sections. In mobile layouts, they collapse or move off-canvas to save space. A well-designed sidebar keeps navigation predictable, reduces clicks, and scales as your app grows.
Bootstrap makes this easier by offering a strong grid system, utility classes, and responsive helpers. That’s why Bootstrap sidebars are still widely used in production apps today.
Let’s Explore Top Open Source Bootstrap Sidebars
Below is a mix of modern sidebar templates and community-built examples. Some are full dashboard solutions, while others are simple layouts you can customize freely.
MaterialM Sidebar
MaterialM comes with a clean, Material-inspired sidebar built for modern admin dashboards. The layout is easy to follow and works well when your application has many pages or sections. It’s a good fit for dashboards where structure and consistency matter.
Modernize offers a simple and modern Bootstrap sidebar that focuses on spacing and readability. It feels lightweight and works especially well for analytics dashboards, internal tools, and SaaS admin panels where clarity is important.
Studiova includes one of the most visually polished sidebars in this list. It’s designed for design startups, SaaS products, creative websites, and modern dashboards where navigation should look clean and professional. The sidebar adapts smoothly across devices and feels ready for real production use.
Matdash provides a structured Bootstrap sidebar designed around real SaaS workflows. It works well for dashboards that need multiple sections while keeping navigation simple and easy to follow.
MaterialPro offers a professional sidebar inspired by Material UI concepts. It’s built for large dashboards where clear navigation and scalability are important.
FreeDash is a free Bootstrap admin template that includes a ready-to-use sidebar. It’s a solid option for small projects, prototypes, or internal tools where you want something functional without extra setup.
Spike provides a simple and flexible Bootstrap sidebar that’s easy to customize. It works well for long-term admin projects and for teams maintaining existing Bootstrap applications.
This is a simple collapsible sidebar built with plain Bootstrap. It’s a good starting point if you want full control over behavior without adding extra libraries.
Which Bootstrap sidebar is best for SaaS applications?
Studiova, Modernize, and MaterialM are strong choices for SaaS projects. They focus on responsiveness, clean navigation, and layouts that scale with growing products.
Are Bootstrap sidebars still relevant today?
Yes. Bootstrap is still widely used in real-world dashboards and enterprise applications. Sidebars remain a reliable navigation pattern, especially for admin and SaaS platforms.
Should I choose a template or a sidebar snippet?
If you’re building a full dashboard, a template saves time. If you want full control or are adding navigation to an existing project, a sidebar snippet is often enough.
Wrapping Up
Building a good sidebar is not about adding more features; it’s about making navigation feel natural.
Modern Admin Templates like Modernize, Spike and MaterialM , show how sidebars can be clean, responsive, and ready for real-world use. Their open-source nature and multi-framework support make them practical for teams working across different tech stacks.
At the same time, community-built sidebars are great for learning, prototyping, and custom solutions. With so many open source options available, you don’t need to start from scratch—you just need to choose what fits your project best.
If you’ve built or discovered a useful Bootstrap sidebar, feel free to share it. Good sidebars help the entire developer community build better applications.
In 2026, dashboards have started to become more important than ever before, especially when it comes to designing and developing intuitive and data-rich interfaces. Every management tool, analytical dashboards, or CRM systems, including an ecommerce dashboard require a template to ensure smooth interactions and a seamless user experience. As with the surge in importance of aesthetic and responsive functionality, this modern dashboard design has everything it takes to excel in the industry.
Whether you are a developer looking to embed the latest designs in your web application or a business looking to streamline your operations and increase productivity, these dashboard templates and designs come in handy when you wish to design aesthetic and functional web interfaces.
Let’s dive into the best designs of Figma, offering customizable features and modern layouts that are perfect for any project.
Tips for Choosing the Final Dashboard Design
When selecting the Figma or coded dashboard designs for your project, consider the following key elements:
Responsive Layouts – Make sure the design can work on any device or screen.
Customizability – Make sure the template is easy to change for color patterns, elements, and designs.
User-Friendliness – Keep interface designs handy and ensure they are easy to use to avoid frustrating the user.
Integration with Modern Frameworks – Having designs that work with React, Next.js, and Tailwind will make your integration easier.
Light/Dark Mode Support – Some designs provide both modes and let users pick whichever they prefer.
Explore top admin ui designs , including options like the Tailwind dashboard, which offer customizable features and sleek, modern layouts that are ideal for any project.
Modernize
Modernize is a sleek, minimalist react template that can be used for a range of applications. A web application that has a large or small complexity will benefit from Modernize’s clean and responsive design. Developers will also be pleased to see that it is easy to use and comes with a coded version and a Figma file.
Key Features:
Simple and clean layout
Fully responsive for mobile and desktop devices
Light and dark mode themes are available for customization
Figma and coded export-ready files available
Charts, forms, and tables for advanced data management
Inspired by Google’s Material Design, MaterialM’s design is perfect for creating powerful and attractive dashboards. The design is mobile responsive and customizable to promote user-centered design. Developers love that the Figma file is ready for customization and the coded file is ready for use.
Key Features:
Mobile and desktop responsive design
Responsive layout that follows Material Design
Widgets and other custom components
Frictionless modern transitions between components
Chairs, tables, and other components in modern design
For developers who want to efficiently design clean, simple admin interfaces, the Dashboard UI Kit is a wonderful tool. This free design resource is versatile, responsive, and includes the backbone components for a dashboard, such as forms, charts, and tables.
Asanah is a modern, task-management-focused dashboard interface perfect for project managers and team collaboration. This template comes with several tools and components designed to manage tasks, track milestones, and keep teams on track.
Key Features:
Task and milestone management tools
User-friendly interface with real-time progress updates
Customizable widgets and data views
Includes charts, project boards, and automated reminders
This template is best for people who want to focus on getting a neat and uncomplicated user interface while developing for small to average businesses. This user-friendly design has options to add Widgets such as tables and charts.
Key Features:
Simple design with minimal distractions
Easy-to-use components for integration
Fully responsive across all devices
Includes essential data visualization tools like graphs and charts
Venus offers a highly customizable dashboard ui kit suitable for developers who need to create powerful, responsive, and easy-to-navigate user interfaces. It’s perfect for complex applications requiring a clean yet detailed UI.
Key Features:
Fully responsive and optimized for all screen sizes
Includes a variety of customizable widgets
Data visualization tools for charts, graphs, and statistics
The Analytics Dashboard is perfect for data-driven projects, offering a clean design for tracking KPIs, analytics, and performance data. It’s fully responsive and comes with built-in charts, tables, and reports.
Custom-built for Learning Management Systems, Designo serves educational institutions and businesses that need to organize and manage course and student information. Designo offers a streamlined platform for admins to monitor student assignments, grades, and progress.
Key Features:
Tailored for use in learning management systems
Facilitates tracking grades, assignments, and course progress
Variety of customizable elements for different needs
This flexible, customizable dashboard template is designed to provide maximum flexibility for developers. With its comprehensive design elements, it’s a great option for building any type of admin panel or data management tool.
Key Features:
Flexible and customizable design
Fully responsive and optimized for mobile
Easy-to-use components for quick integration
Includes charts, tables, and reports
Ideal for admin panels and data-driven applications
HR Dashboard is designed for human resource management, so you can monitor employee data, attendance, and performance. It’s sleek, efficient, and designed with all the resources you need to streamline your HR management.
Key Features:
HR-focused design with employee tracking tools
Includes attendance tracking, leave management, and performance reports
Designed for SaaS companies, the SaaS B2B Dashboard allows you to track customer and sales data and other important metrics. If you need an operational overview, it’s an easy-to-use system designed for SaaS businesses.
Modern Dashboard offers a sleek, modern interface with all the essential features for data management. It’s perfect for any business that needs an intuitive admin interface with real-time analytics and reporting.
Key Features:
Sleek, modern design with essential data tools
Includes real-time data updates and reporting
Easy integration with backend systems
Customizable charts and tables for data presentation
Q1: How do I choose the best admin panel design template for my project?
Consider factors like responsiveness, customization options, ease of integration, and the specific needs of your project. If you need advanced features, go for a paid template with a comprehensive set of tools.
Q2: Can I modify these dashboard templates?
Almost all the templates can be personalized, including the structure, theme, and new elements.
Q3: Do these templates work with modern frameworks?
Absolutely! The templates mentioned above are dashboard designs only, so you can build them in any framework that fits your needs. If you’re looking for ready-to-use, pre-coded templates, check out Modernizeor MaterialM.
Conclusion
The best dashboard template designs for 2026 focus on being easy to use, flexible, and practical. Whether you need a creative dashboard design for a startup or a professional one for a big company, these templates give you a solid starting point to build responsive, user-friendly dashboards. Check out the options above, test the dashboard layout with their live previews, and download the designs to start your next project.
A good ecommerce dashboard template allows developers and business owners to monitor orders, sales, revenue, customers, and stock in one place. Pre-built templates save professional, data-driven experiences and weeks of development. Why spend time building templates when you can spend that time building functionality or business logic that improves your bottom line?
In this article, we’ve compiled 13 of the best dashboard ecommerce templates. These are developers’ favorites due to their clean UI, modern stack, and effortless integration.
Why a Good E-Commerce Dashboard Template Matters
Reduce development time – instead of building UI from scratch, you can adapt a template.
Standardize metrics – you and your stakeholders share a single source of truth.
Plug & play with data pipelines – many templates are designed to integrate with APIs or BI tools.
Scalable and maintainable – clean code, modular widgets, theming.
In short, using an ecommerce admin template gives you a jumpstart, consistency, and reduces time to value.
What to Look for in an Ecommerce Template
Before diving into examples, here’s a checklist:
Feature
Why it’s important
Modular widgets/components
Easily add, remove, or rearrange KPI panels
Data connectors / API support
Integration with Shopify, WooCommerce, BigQuery, etc.
Responsive & mobile support
Key metrics should adapt to smaller screens
Theming / Styling flexibility
Match your brand’s look & feel
Performance & load optimization
Dashboards must be snappy under real load
Role-based access/permissions
Show/hide panels based on roles (admin, manager, etc.)
Spike React Tailwind
Spike React Tailwind is modern and responsive. It also has a clean, structured code and several widgets ready for use.
Modernize Tailwind Next.js is an eCommerce dashboard. It is production-ready as a dashboard and employs Next.js. It is optimized for speed, SEO, and scalability.
Key Features:
Built on Next.js 15 + Tailwind CSS
eCommerce specific pages (orders, products, revenue)
Server-side rendering for SEO
RTL support and responsive layout
Completely customizable elements
Suitable for developers who are targeting server-side rendering support and best-in-class performance.
Q1: Can I customize these dashboards for my business needs?
Absolutely! You can modify all the templates, which include adding additional widgets and connecting APIs.
Q2: Which tech stack should I choose, React, Next.js, or Angular?
If SEO and SSR are important, go with Next.js. For enterprise Angular projects, MatDash is a superb choice.
Q3: Are these templates mobile-friendly?
Yes! All the templates are responsive and designed to be used easily on desktops, tablets, and smartphones.
Conclusion
A well-built ecommerce template saves developers valuable time, keeps analytics consistent, and delivers a better experience to stakeholders. Whether you prefer React, Next.js, Angular, or Bootstrap, there’s a perfect template for you in this list.
With ever so increasing rise in popularity of NextJs, it has become quite a standard to use it for server-side React web applications. So, that means the NextJs cheat sheet will be your main asset going forward.
It gets all the features of React.js – the JavaScript’s UI library to build components and adds so many additional features that sometimes as a NextJs developer it’s hard to catch up on the different code snippets, commands to run, packages to install.
Whether you’re a beginner or a seasoned pro, this cheat sheet will serve as a valuable resource. Now, let’s explore the specifics that can greatly enhance your NextJs projects. You can also check WrapPixel’s ready to use Nextjs Templates to speed up your development workflow.
This NextJs Cheat sheet will be solution to all your next js coding problems.
To solve this issue, we have created a to-the-point NextJs cheat sheet of all the features that will benefit all developers – be they a beginner or a pro. Let’s dive in!
What is NextJs?
If you don’t know what is nextjs. Then let me tell you. According to its definition on the official docs:
Next.js is a flexible React Framework that gives you building blocks to create seo friendly fast Web Applications.
Basically, it provides some of the crucial features and building blocks on top of a standard React.js application to make a modern website and apps.
NextJs Cheat Sheet
Given below is the Next.js cheat sheet that you can use in your next web project.
Create App Using Nextjs Cheat Sheet
In this first step of the NextJs cheat sheet, we will create a NextJs app, the recommended process is to use the official create-next-app command which sets up all the necessary files, folders, and configuration automatically.
This page will be available at http://localhost:3000/demo of your local environment.
App Router
Next.js has always been known for its file-system-based routing, a simple yet powerful way to define pages using just the filesystem. For example, in the classic Pages Router, you could create a route like this: No additional configuration needed just create a file under the pages/ directory and Next.js would automatically map it to a route. This simplicity helped Next.js gain widespread adoption. But as the framework matured, so did the needs of developers.
They began asking for:
Better layout support (nesting, reusability)
Per-page loading and error states
Server components and streaming
More granular control over HTML structure and styling
To address these needs, Next.js introduced the App Router in version 13.
// Pages Router// This "global layout" wraps all routes. There's no way to// compose other layout components, and you cannot fetch global// data from this file.exportdefaultfunctionMyApp({Component,pageProps}){return<Component {...pageProps} />;}
// New: App Router ✨// The root layout is shared for the entire applicationexportdefaultfunctionRootLayout({children}){return (<htmllang="en"><body>{children}</body></html> );}
// Layouts can be nested and composedexportdefaultfunctionDashboardLayout({children}){return (<section><h1>Dashboard</h1>{children}</section> );}
// Pages Router// This file allows you to customize the <html> and <body> tags// for the server request, but adds framework-specific features// rather than writing HTML elements.import{Html,Head,Main,NextScript}from'next/document';exportdefaultfunctionDocument(){return (<Html><Head /><body><Main /><NextScript /></body></Html> );}
// New: App Router ✨// The root layout is shared for the entire applicationexportdefaultfunctionRootLayout({children}){return (<htmllang="en"><body>{children}</body></html> );}
A lot of other relevant feature requests for our routing system could be addressed at the same time as we had the chance to design a new file-system router. For instance:
In the past, app.js could only import global stylesheets from outside npm packages (such as component libraries). It was not the best development experience. Any CSS file can be imported (and placed) in any component using the App Router.
Previously, using your application was restricted until the full page was hydrated if you choose to use server-side rendering with Next.js (through getServerSideProps). We have refactored the architecture with the App Router to be fully integrated with React Suspense, allowing us to selectively hydrate portions of the page without preventing other UI components from being interactive.
Turbopack
Through next dev –turbo and soon your production builds (next build –turbo), Turbopack, our new bundler that we are testing and stabilising through Next.js, helps speed up local iterations while working on your Next.js application.
We have witnessed a steady increase in popularity since the alpha release of Next.js 13 as we have worked to fix problems and add support for lacking functionality. To get feedback and increase stability, we have been testing Turbopack on Vercel and with numerous Vercel clients running substantial Next.js websites. We appreciate the community’s assistance in testing and alerting our team to bugs.
We are now prepared to advance into the beta phase after six months.
Webpack and Next.js currently have more features than Turbopack does. Support for those functionalities is being tracked in this issue. The majority of use cases ought to be supported today, though. In order to continue addressing bugs from greater adoption and get ready for stability in a future version, we are releasing this beta.
Turbopack’s incremental engine and cache layer are being improved, and this will eventually speed up not only local development but also production builds. Keep an eye out for a future release of Next.js that will allow you to run next build –turbo for instant builds.
Use next dev –turbo to test out the Turbopack beta in Next.js 13.4.
File-Based Metadata API
By exporting a Metadata object from a layout or page, you can define metadata (such as title, meta, and link tags inside your HTML head element) using the new Metadata API that was introduced in Next.js 13.2.
// either Static metadataexportconst metadata ={title:'Home',};// Output:// <head>// <title>Home</title>// </head>// or Dynamic metadataexportasyncfunctiongenerateMetadata({params,searchParams}){constproduct=awaitgetProduct(params.id);return{ title:product.title};}// Output:// <head>// <title>My Unique Product</title>// </head>exportdefaultfunctionPage(){}
The Metadata API now supports new file conventions in addition to configuration-based metadata, making it simple to quickly alter your pages for better SEO and online sharing:
At the Next.js Conference, @vercel/og was put to the test by creating over 100,000 dynamic ticket pictures for each guest. We are thrilled to introduce dynamically generated images to all Next.js applications without the requirement for an external package thanks to widespread adoption among Vercel clients and over 900,000 downloads since the release.
To create images, you may now import ImageResponse from next/server:
Route Handlers and file-based Metadata are only two of the Next.js APIs that work well with ImageResponse. For instance, you can create Open Graph and Twitter pictures at build time or dynamically at request time using ImageResponse in an opengraph-image.tsx file.
Static Export for App Router
Fully static exports are now supported by the Next.js App Router.
A static website or Single-Page Application (SPA) can be used as a starting point, and you can later upgrade to employ Next.js features that demand a server.
As part of the next build process, Next.js creates an HTML file for each route. A strict SPA can be broken down into separate HTML files with the help of Next.js to prevent extra JavaScript code from being loaded on the client-side, hence lowering the bundle size and enabling quicker page loads.
The app router’s new features, like static Route Handlers, Open Graph images, and React Server Components, are compatible with Static Export.
Like traditional static-site generation, Server Components, for instance, will execute throughout the build and render the components into static HTML for the initial page load and a static payload for client movement across routes. Before, you had to perform the next export before using Static Export in the pages directory. However, when output: ‘export‘ is set, the next build will produce an out directory thanks to the next.config.js option. The app router and pages directory can both be configured in the same way. Therefore, the subsequent export is no longer necessary.
Parallel Routes and Interception
Parallel Routes and Intercepting Routes are two brand-new dynamic conventions that Next.js 13.3 introduces to help you create complex routing scenarios. With the help of these features, you can display multiple pages in the same view, such as with intricate dashboards or modals.
You can simultaneously render one or more pages in the same view that can be accessed separately using Parallel Routes. It can also be used to render pages conditionally.
Named “slots” are used to build parallel routes. According to the @folder convention, slots are defined:
exportdefaultasyncfunctionLayout({children,user,team}){constuserType=getCurrentUserType();return (<>{userType ==='user'? user : team}{children}</> );}
The @user and @team parallel route slots (explicit) in the aforementioned example are conditionally produced based on your reasoning. The implicit route slot children does not require mapping to a @folder. Dashboard/page.js, for instance, is identical to Dashboard/@children/page.js.
By “masking” the browser URL, you can load a new route within the existing layout by intercepting routes. When the context of the current page must be preserved, such as when expanding a photo in a feed through a modal while the feed is kept in the modal’s background, this is helpful.
Style Your Next.js App
There are many ways to style your apps in this step of the NextJs cheat sheet, some of the common methods are:
Global styling: import the global styles.css in your pages/_app.js where these styles will apply to all pages and components in your app as:
Component-Level CSS: NextJs supports CSS Modules where you can name the files as [name].module.css and then import it on a specific component. Here’s an example:
In this step of the NextJs cheat sheet, to optimize images you should use the built-in Image component. Install it in your project as:
import Image from'next/image'
Then give it an src attribute as shown in the following example:
import Image from'next/image'const myLoader =({src,width,quality})=>{return`https://example.com/${src}?w=${width}&q=${quality ||75}`}const MyImage =(props)=>{return (<Imageloader={myLoader}src="me.png"alt="Picture of the author"width={500}height={500} /> )}
Optimize Fonts
In this step of the Next.js cheat sheet, to optimize fonts you should use the built-in next/font module which loads fonts locally or from Google Fonts with performance best practices like automatic preloading, subsetting, and font-display swapping.
import{Inter}from'next/font/google';const inter =Inter({subsets: ['latin'],display:'swap',});
First, import a font from next/font/google (for Google Fonts) or next/font/local (for self-hosted fonts)
Custom 404 Pages
To create custom 404 page, create a 404.js file in the pages folder
exportdefaultfunctionCustom404(){return<h1>404 - Page Not Found</h1>}
You can also create a 500.js file for the server error 500 page
Next.js 15 enforces stricter usage of request objects in Server Components. You can no longer access request methods like req.json() or req.body() directly in the App Router unless they’re awaited properly inside a POST handler.
Asynchronous Cookies API
In Next.js 15, the cookies() API has transitioned from synchronous to asynchronous. This means you now need to use await cookies() instead of calling it directly. The change allows for better support of async storage mechanisms and prepares the framework for future features like enhanced streaming and edge compatibility.
In Next.js 15, the headers() API has also moved from synchronous to asynchronous. You now need to await headers() before accessing header values. This update ensures compatibility with future enhancements like streaming, middleware, and edge rendering.
In Next.js 15, layouts are now asynchronous by default meaning your layout files can use async/await without any special configuration. This is especially useful for loading data at the layout level (e.g., fetching user or theme preferences).
In Next.js 15, Route Handlers are now asynchronous by default. This means you can directly use await inside route handler functions (e.g. GET, POST) without manually wrapping them in async.
Here’s an example to fetch data at request time which pre-renders the result it gets back from the data source:
functionPage({data}){// Code to render the `data`}exportasyncfunctiongetServerSideProps(){constres=awaitfetch(`https://.../data`)constdata=awaitres.json()return{ props:{data}}}exportdefault Page
getStaticPaths: if you want to dynamically generate routes on your app alongside with getStaticProps then, getStaticPaths will pre-render all the paths provided to it as:
Note that the props here must be passed to the page component as props. An example of its usage when you want the data to fetch from a CMS is as follows:
Incremental Static Regeneration(ISR): if you want to create or update existing static pages after you’ve built your site, then ISR allows you to statically generate on a per-page basis. This means that now you don’t need to rebuild the entire site from scratch.
For this to work, you just need to add the revalidate prop to the getStaticProps method:
exportasyncfunctiongetStaticProps(context){return{ props:{}, revalidate:5// this means the request to re-generate the page will berevalidated once in every 5 seconds}}
Fetch data on client-side: this can be done in two different ways — either via the useEffect hook as:
functionUser(){const[data,setData]=useState(null)const[isLoading,setLoading]=useState(false)useEffect(()=>{setLoading(true)fetch('api/user-data').then((res)=>res.json()).then((data)=>{setData(data)setLoading(false)})}, [])if (isLoading) return<p>Loading user data...</p>if (!data) return<p>No user data found</p>return (<div><h1>{data.name}</h1><p>{data.bio}</p></div> )}
or via the SWR library which handles caching, revalidation, focus tracking, re-fetching on intervals, and more as:
import useSWR from'swr'const fetcher =(...args)=>fetch(...args).then((res)=> res.json())functionUser(){const{data,error}=useSWR('/api/user-data',fetcher)if (error) return<div>Failed to load user data</div>if (!data) return<div>Loading user data...</div>return (<div><h1>{data.name}</h1><p>{data.bio}</p></div> )}
Linting Your Code
You can use ESLint out-of-the-box for linting. Simply add the following script to the package.json file:
"scripts": {"lint":"next lint"}
Now you can run npm run lint or yarn lint to start the linter. If you are using ESLint in a monorepo where NextJs isn’t installed in your root directory, you just simply add the rootDir to your .eslintrc file:
And then add prettier to your existing ESLint configuration file:
{"extends": ["next","prettier"]}
TypeScript Support
TypeScript support is also one of the NextJs cheat sheets. To use TypeScript with NextJs when you start an app, use the create-next-app command along with the –ts or –typescript flag:
This will spin up a new NextJs project with all the Typescript files and components without any extra configuration.
But if you want to integrate TypeScript in an existing project then, create a new tsconfig.json file at the root of the project directory. Then run npm run dev or yarn dev, with this Next.js will guide you through the installation of the required packages to finish setting up TypeScript integration.
Using Scripts
We are going to use scripts in this step of the NextJs cheat sheet, the native HTML <script> element is replaced by next/script component in NextJs. Here’s an example of loading a Google Analytics script:
In the next step of the NextJs cheat sheet, NextJs has a file-system-based router that works on the concept of pages. You can either have index routes like pages/index.js which map to / and pages/blog/index.js which map to /blog.
Or you can have nested routes where it supports nested files. For example, a file located on pages/blog/my-post.js will route to /blog/my-post.
For dynamic routes, you need to use the bracket syntax so that it can match named parameters. For example, pages/[username]/settings.js will map to /johndoe/settings.
The <Link> component is used to do client-side route transitions. First, you need to import it as:
import Link from'next/link'
Then, use it in a component:
import Link from'next/link'functionHome(){return (<ul><li><Linkhref="/"><a>Home</a></Link></li><li><Linkhref="/about"><a>About Us</a></Link></li><li><Linkhref="/blog/hello-world"><a>Blog Post</a></Link></li></ul> )}exportdefault Home
For dynamic paths, you can use string interpolation to create the desired path:
import Link from'next/link'functionPosts({posts}){return (<ul>{posts.map((post)=> (<likey={post.id}><Linkhref={`/blog/${encodeURIComponent(post.slug)}`}><a>{post.title}</a></Link></li> ))}</ul> )}exportdefault Posts
API Routing
Any file inside the pages/api folder is mapped to /api/* which will be treated as an API endpoint. For example, to return a JSON response with an OK status code of 200, you can export a handler function with req and res passed as parameters:
For example, here is an example where middleware is used for logging:
import{NextRequest}from'next/server'// Regex for public filesconst PUBLIC_FILE =/\.(.*)$/exportdefaultfunctionmiddleware(req:NextRequest){// Only log for visited pagesif (!PUBLIC_FILE.test(req.nextUrl.pathname)) {// We fire and forget this request to avoid blocking the request until completion// and let logging occur in the backgroundfetch('https://in.logtail.com',{ method:'POST', headers:{'Content-Type':'application/json', Authorization:`Bearer ${process.env.LOGTAIL_TOKEN}`,}, body:JSON.stringify({ message:'Log from the edge', nested:{ page:req.nextUrl.href, referrer:req.referrer, ua:req.ua?.ua, geo:req.geo,},}),})}}
Authentication
There are many different ways to authenticate a user in a NextJs app. Some of the common ones are:
Authenticating statically generated pages: here, your page can render a loading state from the server after which it will fetch the user data from the client side. In the following example, the page renders a loading skeleton state and once the request is met, it shows the user’s name:
import useUser from'../lib/useUser'import Layout from'../components/Layout'const Profile =()=>{// Fetch the user client-sideconst{user}=useUser({ redirectTo:'/login'})// Server-render loading stateif (!user||user.isLoggedIn===false) {return<Layout>Loading...</Layout>}// Once the user request finishes, show the userreturn (<Layout><h1>Your Profile</h1><pre>{JSON.stringify(user,null,2)}</pre></Layout> )}exportdefault Profile
Authenticating server-rendered pages: here you need to export an async getServerSideProps() function from a page by which NextJs will pre-render this page on each request. Here’s an example where if there is a session, then the user is returned as a prop to the Profile component:
import withSession from'../lib/session'import Layout from'../components/Layout'exportconst getServerSideProps =withSession(asyncfunction({req,res}){const{user}=req.sessionif (!user) {return{ redirect:{ destination:'/login', permanent:false,},}}return{ props:{user},}})const Profile =({user})=>{// Show the user. No loading state is requiredreturn (<Layout><h1>Your Profile</h1><pre>{JSON.stringify(user,null,2)}</pre></Layout> )}exportdefault Profile
Authenticating with third-party providers: for common authentication providers like Auth0, Firebase, Supabase, etc, you can take a look at the official GitHub repository for examples of how to set up and configure your own NextJs app.
Testing
The last step of the NextJs cheat sheet, Just like with authentication, testing can be done in a lot of different ways and with different testing tools. Here’s how to setup testing with common tools:
Testing with Cypress: start off with the with-cypress example to quickly start a NextJs app with Cypress as:
Then add it to the scripts field of your package.json file:
"scripts": {..."cypress": "cypress open",}
Finally, run Cypress with the following command:
npm run cypress
To create a Cypress test file. Simply create a file under cypress/integration/app.spec.js as:
describe('Navigation',()=>{it('should navigate to the about page',()=>{// Start from the index pagecy.visit('http://localhost:3000/')// Find a link with an href attribute containing "about" and click itcy.get('a[href*="about"]').click()// The new url should include "/about"cy.url().should('include','/about')// The new page should contain an h1 with "About page"cy.get('h1').contains('About Page')})})
Testing with Jest and React Testing Library: again you can use it quickly with the community provided with-jest example while you spin off a new Next project:
Or manually, you can install Jest, React Testing Library, and Jest DOM packages:
npm install --save-dev jest @testing-library/react @testing-library/jest-dom
Then create a jest.config.js file in the project’s root directory:
const nextJest =require('next/jest')const createJestConfig =nextJest({// Provide the path to your NextJs app to load next.config.js and .env files in your test environmentdir:'./',})// Add any custom config to be passed to Jestconst customJestConfig ={// Add more setup options before each test is run// setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],// if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to workmoduleDirectories: ['node_modules','<rootDir>/'],testEnvironment:'jest-environment-jsdom',}// createJestConfig is exported this way to ensure that next/jest can load the NextJs config which is asyncmodule.exports=createJestConfig(customJestConfig)// Add a test script to the package.json file:"scripts": {..."test": "jest --watch"}// Then create a Jest test file under __tests__/index.test.jsx as:import{render,screen}from'@testing-library/react'import Home from'../pages/index'describe('Home',()=>{it('renders a heading',()=>{render(<Home />)constheading=screen.getByRole('heading',{ name:/welcome to next\.js!/i,})expect(heading).toBeInTheDocument()})})
To run the test simply execute the npm run test command.
In this article, you got to know about the NextJs Cheat Sheet , and how it helps in making modern React-based websites and apps. Then you saw how to set up a NextJs project, how to fetch data, optimize assets, add TypeScript support, use linters, integrate testing tools, and more!
In conclusion, having a NextJs Cheat Sheet can greatly benefit developers working with this powerful framework. Providing a quick reference guide to the most commonly used features and functionalities enables developers to work more efficiently and effectively.
A NextJs Cheat Sheet serves as a handy tool for both beginners and experienced developers. It helps reduce the time spent searching for syntax or configuration details, allowing developers to focus more on writing clean and optimized code.
Additionally, a cheat sheet can also aid in improving code quality by promoting best practices and highlighting common pitfalls to avoid. It acts as a reliable companion ensuring developers follow the recommended guidelines while developing their NextJs applications.
Overall, having access to a comprehensive NextJs Cheat Sheet is invaluable for any developer looking to streamline their workflow and enhance their productivity. Whether you’re building small projects or large-scale applications, this resource will undoubtedly prove to be an essential asset in your development toolkit.