Source Freeze

  • Home
  • iOS
  • Swift
  • Cross-Platform
  • About
  • Contact
Home » nextjs

How to disable server side rendering in nextjs

December 20, 2023 by Source Freeze Leave a Comment

When working with Next.js, controlling whether your application renders content on the server-side or client-side can significantly impact its performance and behaviour. Server-side rendering (SSR) can sometimes be unnecessary or less suitable for certain projects, and fortunately, Next.js provides ways to disable SSR when needed. In this blog, we’ll learn how to disable server side rendering in Nextjs

how to disable server side rendering in nextjs
how to disable server side rendering in nextjs

Understanding Rendering Methods in Web Development: CSR, SSR, and SSG

In the world of web development, how your web application renders content can significantly impact its performance, SEO, and user experience. Three primary rendering methods—Client-Side Rendering (CSR), Server-Side Rendering (SSR), and Static Site Generation (SSG)—play crucial roles in shaping the behavior and efficiency of modern web applications.

Client-Side Rendering (CSR):

CSR involves loading a web page’s framework and content entirely on the client’s side, typically using JavaScript. When a user requests a page, the server sends a basic HTML file, and then the client-side JavaScript framework takes over, fetching data from APIs and rendering the page content dynamically. This method enhances interactivity but might lead to slower initial loading times, especially on slower devices or networks.

Server-Side Rendering (SSR):

SSR generates the HTML for a web page on the server before sending it to the client. When a user requests a page, the server processes the request, fetches data, and generates an HTML page with populated content. This pre-rendered HTML is then sent to the browser, providing faster initial loading times and better SEO due to the presence of content in the HTML.

Static Site Generation (SSG):

SSG involves generating HTML files during the build time of the application, rather than on each request. This method pre-renders the entire website as static HTML files, which are then served to users. SSG offers the best performance as the content is already available and doesn’t require server processing for each request. However, it might not be suitable for highly dynamic content.

Let’s learn one approach using react-no-ssr todisable server-side rendering in Next.js:

Using react-no-ssr

react-no-ssr is a package that allows components to be excluded from SSR. It ensures that certain parts of your application are only rendered on the client-side, bypassing SSR. Here’s how you can use it:

First, install the react-no-ssr package via npm or yarn:

npm install react-no-ssr
# or
yarn add react-no-ssr

Let’s say you have a component that you want to render only on the client-side. Import the NoSSR component from react-no-ssr:

import dynamic from 'next/dynamic';
import NoSSR from 'react-no-ssr';

const DynamicComponent = dynamic(() => import('../components/YourComponent'), {
  ssr: false,
});

const YourPage = () => {
  return (
    <div>
      {/* Components inside NoSSR will be rendered only on the client-side */}
      <NoSSR>
        <DynamicComponent />
      </NoSSR>

      {/* Other components will follow SSR rules */}
      <YourOtherComponents />
    </div>
  );
};

export default YourPage;

The dynamic function from next/dynamic is used to dynamically load the component. Setting ssr to false ensures it’s excluded from SSR. The DynamicComponent will only be rendered on the client-side, while other components will follow the SSR rules of Next.js.

Using next/dynamic

next/dynamic is a Next.js function that allows for dynamic importing of components. It enables loading components asynchronously, which can be particularly useful when you want to control server-side rendering or optimize the initial loading of a page.

We’ll ensure if we have Next.js installed in our project. next/dynamic is a built-in Next.js feature, so no separate installation is required.

Let’s say you have a component named YourComponent that you want to render only on the client-side:

import dynamic from 'next/dynamic';

const DynamicComponent = dynamic(() => import('../components/YourComponent'), {
  ssr: false, // Set ssr to false to exclude from server-side rendering
});

const YourPage = () => {
  return (
    <div>
      {/* Render the dynamically imported component */}
      <DynamicComponent />
      
      {/* Other components */}
    </div>
  );
};

export default YourPage;

The dynamic function from next/dynamic operates by asynchronously importing components at runtime rather than during the initial server render. When using dynamic, it takes two arguments: a function that imports the component and an options object that can include properties like ssr.

For instance, consider importing a component named YourComponent. By employing dynamic, this import happens on the client-side when the component is required, ensuring that it’s not bundled with the server-rendered HTML. The key here is the ssr: false property within the options object passed to dynamic, explicitly instructing Next.js to exclude this component from server-side rendering. Consequently, when the page loads, YourComponent will be fetched and rendered exclusively on the client-side, optimizing performance by reducing initial load times. This fine-grained control over SSR helps in managing the balance between rendering components on the server for SEO and initial page loads while offloading others for better client-side interactivity.

NextJS has also added an official way to make this work, checkout there official docs on lazy loading here

Using a String (‘use client’)

In Next.js, a specific string at the top of a component file can be used as a workaround to trigger client-side rendering for that component. Here’s how you can do it:

'use client'

import React from 'react';

const YourComponent = () => {
  return (
    <div>
      {/* Your component content */}
    </div>
  );
};

export default YourComponent;

Adding the string 'use client‘ at the top of the component file acts as a signal to Next.js that this component should be rendered on the client-side.This technique exploits Next.js behavior to exclude certain components from server-side rendering.

Note: While this technique works, it’s considered more of a workaround and might not be officially documented or supported. It’s important to test thoroughly and ensure it aligns with the application’s requirements.

Conclusion

In this blog, we’ve explored methods to control how our Next.js apps load. We’ve uncovered next/dynamic, a tool letting us bring in components exactly when needed. Plus, we explored react-no-ssr, a way to say “hey, don’t server-render this one!” And also learnt about the simple but effective “use client” hint, making components show up just on the client-side.

Our other blogs:

  • Capitalize First letter in JavaScript
  • Remove all Classes from an Element in JavaScript
  • Append Text to a Textarea in JavaScript
  • How to create a style tag using JavaScript
  • Remove all Classes from an Element in JavaScript
  • Hide/Show an Element in JavaScript

Filed Under: javascript, NextJS Tagged With: beginner, javascript, nextjs, web developer

How do you get the current url in Nextjs?

December 15, 2023 by Source Freeze Leave a Comment

In this blog, we will explore the topic of retrieving the current URL in Next.js, a powerful React framework. Understanding how to obtain the current URL is crucial for various web development scenarios. We’ll explore the steps to achieve this and provide real life code examples to get the current url in Nextjs.

How do you get the current url in Nextjs?
How do you get the current url in Nextjs?

Getting Started:

To kick things off, let’s understand why obtaining the current URL is important in web development. Often, we encounter situations where we need to dynamically update content based on the URL or perform specific actions. In Next.js, achieving this is straightforward, and we will guide you through the process.

Using useRouter Hook for Client-Side Access

The useRouter hook is a cornerstone for client-side URL access in Next.js. Import it using import { useRouter } from 'next/router' to utilize its functionalities within your components.

import { useRouter } from 'next/router'

function YourComponent() {
  const { asPath, pathname } = useRouter();

  // Your component logic

  return <h2>Your Component</h2>
}

Here, asPath holds the full page path, while pathname encapsulates the page’s specific path, even with dynamic routing parameters.

The useRouter hook serves as a fundamental tool for accessing URL details on the client side within Next.js components.

Breakdown:

  • asPath: Represents the complete URL path, including query parameters and hash fragments. It’s valuable for capturing the entire route a user is visiting.
  • pathname: Indicates the specific page path, even with dynamic routing parameters. This property is useful for targeting specific routes within your application.

Practical Use:

  • Dynamic Page Rendering: Determine the specific route or page being accessed by extracting data from asPath or pathname.
  • Conditional Rendering: Implement conditional logic based on the current URL path or query parameters using these properties.

Unveiling URL Details on the Server

In scenarios requiring Server-Side Rendering (SSR) through getServerSideProps, accessing URL information involves different approaches. Leveraging req.url or query within the getServerSideProps the function offers insights into the URL structure. Moreover, the resolvedUrl property provides the URL without the _next/data prefix, vital for client transitions.

export async function getServerSideProps({ req, query, resolvedUrl }) {
  console.log(req, query, resolvedUrl)
  return { props: {} }
}

Breakdown:

  • req.url: Provides the path, similar to the asPath on the client side.
  • query: Contains query strings and path parameters.
  • resolvedUrl: Offers the URL without the _next/data prefix, enabling smoother client transitions.

Practical Use:

  • Server-Side Data Fetching: Fetch data based on the URL parameters or path accessed during server-side rendering.
  • URL Transformation: Manipulate the URL for specific server-side functionalities or API interactions based on the accessed route.

Static Site Generation and URL Retrieval

For Static Site Generation (SSG) via getStaticProps, the params object holds the defined parameters from the path. This method grants access to crucial parameters, allowing precise handling of page generation.

export async function getStaticProps({ params }) {
  console.log(params)
  return { props: {} }
}

Breakdown:

  • params: Holds parameters defined in the URL path, aiding in precise page generation.

Practical Use:

  • Dynamic Page Generation: Generate static pages based on URL parameters, ensuring dynamic content for specific routes.
  • Custom Page Rendering: Craft pages with dynamic content fetched based on URL parameters for a personalized user experience.

Conclusion

In this blog, we delved into comprehensive methods of obtaining the current URL in Next.js, covering:

  1. Using useRouter Hook for Client-Side Access
  2. Unveiling URL Details on the Server
  3. Static Site Generation and URL Retrieval

Understanding these distinct methods for obtaining URLs in Next.js empowers developers to employ diverse strategies for client-side interactivity, server-side data retrieval, and dynamic page generation.

Our other blogs:

  • Capitalize First letter in JavaScript
  • Remove all Classes from an Element in JavaScript
  • Append Text to a Textarea in JavaScript
  • How to create a style tag using JavaScript
  • Remove all Classes from an Element in JavaScript
  • Hide/Show an Element in JavaScript

Filed Under: NextJS Tagged With: beginner, javascript, nextjs, web developer

Next.js Warning: Extra attributes from the server

December 10, 2023 by Source Freeze Leave a Comment

This blog post will guide you through the annoying “Extra attributes from the server” warning encountered in Next.js 13 and beyond. We’ll explore the causes, multiple solutions, and best practices to keep your development environment clean and free of clutter.

Next.js Warning: Extra attributes from the server

Understanding the Warning

What is the warning?

The warning message ‘Extra attributes from the server’ is often observed in the console when working with Next.js 13 or higher looks like this:

Extra attributes from the server: class,style at html

This red warning indicates a mismatch between the HTML rendered on the server and what’s rendered on the client-side during hydration.

What causes it?

The culprit behind this warning is usually browser extensions, particularly those modifying the web page you’re viewing. Extensions like Grammarly, ColorZilla, and LanguageTool often add attributes to the HTML, causing the inconsistency during Next.js’s hydration process.

Solutions to Eliminate the Warning:

We’ll explore three effective methods to eliminate the warning:

1. Incognito Mode:

The simplest solution is to use your browser’s incognito mode (private mode). This temporarily disables all extensions, preventing them from interfering with Next.js and eliminating the warning. To access incognito mode, press Ctrl + Shift + N (Windows) or Cmd + Shift + N (Mac) on your keyboard.

2. suppressHydrationWarning Prop:

Next.js provides a built-in prop called suppressHydrationWarning that can be set to true on the <body> tag in your root layout. This explicitly tells Next.js to ignore any extra attributes encountered during hydration, effectively suppressing the warning.

Here’s an example:

// Root Layout (app/layout.tsx)

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body suppressHydrationWarning={true}>{children}</body>
    </html>
  );
}

3. Disable or Remove Extensions:

If you prefer a more permanent solution, consider disabling or removing the extensions causing the issue. You can identify the problematic extensions by temporarily disabling them one by one and observing the console for the warning’s disappearance. Alternatively, you can switch to a different browser that doesn’t have the conflicting extensions installed.

Best Practices that can be followed:

While these solutions effectively eliminate the warning, it’s important to remember:

  • Avoid browser extensions in development: Extensions can introduce inconsistencies and unexpected behaviors, especially during development. Consider disabling all extensions while working on your Next.js project for a clean and stable environment.
  • Use dedicated development environment: Consider using a dedicated development environment like a virtual machine or container to isolate your development tools and avoid conflicts with your primary browser extensions.
  • Understand the root cause: While suppressing the warning can be helpful, it’s crucial to understand the underlying cause – browser extensions in this case. Understanding the root allows for informed decision-making and long-term solutions.

By implementing these solutions and best practices, you can maintain a clean development environment and eliminate the annoying “Extra attributes from the server” warning in Next.js.

Thanks for stopping by! Check out more from Source Freeze here!

Filed Under: javascript, NextJS Tagged With: beginner, javascript, nextjs, web developer

How to redirect to another page in next js

January 8, 2023 by Source Freeze Leave a Comment

In this tutorial, we will see how to redirect to another page in next js, there are three ways to redirect one page to another page in nextjs.

  1. Using Link in Next.js
  2. useRouter() Hook by using router.push
  3. config.next.js
  4. Middleware

Let’s see each option in a detailed way.

How to redirect to another page in next js

Using Link Component in Next.JS

Using Link component in nextjs it is like a href tag you can just use the href attribute and mention the redirect URL, please refer the below example.

☞ Check out Next.js & React – The Complete Guide (incl. Two Paths!) (Buy now, offer ends in a few hours)

First we need import the Link from the next/link module

import Link from 'next/link';

// ...

return (
  <div>
    <Link href="/new-url">
      <a>Click here to redirect</a>
    </Link>
  </div>
);

How to redirect to another page using useRouter() Hook onclick

We can use the useRouter hook from next/router to get access to the router object in your functional component, and then we can use the push method to navigate to another page on the buttonn onclick event.

Let’s see an example using userRouter in the below.

import { useRouter } from 'next/router';

function MyComponent() {
  const router = useRouter();

  const handleClick = () => {
    router.push('/new-page');
  };

  return (
    <button onClick={handleClick}>Go to new page</button>
  );
}

While clicking the Go to new page button, it will navigate to the /new-page page.

We can also use the router.push method to pass query parameters to the new page, as mentioned in the below example.

import { useRouter } from 'next/router';

function MyComponent() {
  const router = useRouter();

  const handleClick = () => {
  router.push({
  pathname: '/new-page',
  query: {
    name: 'Source Freeze',
    count: 30,
  },
  });
  };

  return (
    <button onClick={handleClick}>Go to new page</button>
  );
}

This will navigate to the /new-page page and pass the query parameters name and count to it.

How to redirect to another page using config.next.js

We can redirect a one to another page using config.next.js but this is fixed redirect mostly it is used for ther permanent redirect it is not a logic based, in some cases you need to get the benefit SEO for the redirection or permanent redirection we will use this approach, please refer the below to redirect to another page using config.next.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  async redirects() {
     return [
                {
                    source: '/old-page',
                    destination: '/',
                    permanent: true,
                 },
            ]
    },
}
module.exports = nextConfig

Middleware

Next we can achive the redirection using the Middleware, this middleware redirection we can use the conditional based redirection.

Please refer the beloe example.

import {  NextResponse } from 'next/server'
export function middleware(request) {
if ( request.id === 1 ) {
return NextResponse.rewrite(new URL('/page-1', request.url))
} else if (request.id === 2) {
return NextResponse.redirect(new URL('/page-2', request.url))
} else {
return NextResponse.rewrite(new URL('/not-found', request.url))
}
return NextResponse.next()
}

Here in this tutorial we have seen all the options of redirect to another page in next js.

Thanks for reading also you can refer the below tutorial how to get the query params from the URL in NextJS

☞ Check out Next.js & React – The Complete Guide (incl. Two Paths!) (Buy now, offer ends in a few hours)

Filed Under: javascript, NextJS Tagged With: javascript, nextjs

How to get the query parameters from URL in Next JS?

January 5, 2023 by Source Freeze Leave a Comment

In nextjs we can easily get the query params with the use of useRouter() that we can import from 'next/router' then assign userRouter() to the router variable after that using router.query we can get the exact query string values. if you are passing multiple queries also we can get the values from router.query.

☞ Check out Next.js & React – The Complete Guide (incl. Two Paths!) (Buy now, offer ends in a few hours)

how to get the query params from URL in nextjs

Here in the example, we can see the detailed way, how to get the query params from the URL in NextJS it is applicable for single query params or multiple query params.

First, we can see how to pass the query params to the link to the next calling page, refer to the below code.

import Link from "next/link";

<Link href={{ pathname: '/search', query: { keyword: 'source freeze' } }}>

<a>Search</a>

</Link>

Then next we need to get the query params from the URL, here we are three options to get the query params, please refer to the below options.

  1. In Component
  2. Using getServerSideProps Function
  3. In API Routes

First, we can see the option to get query params in the component

Access Query Params in the Component

To get the query params in the component first we need to import the useRouter from the ‘next/router’, then create a variable router and assign the useRouter to that variable, then using router.query we can able to get the exact params, used anywhere on the page.

import { useRouter } from 'next/router';

function Search(props) {
  const router = useRouter();

  // Get the query parameter from the URL
  const { keyword } = router.query;

  return (
    <div>
      The Search Keyword {keyword}.
    </div>
  );
}

export default Search;

Also if you have passed multiple keywords we can easily access them like the one below.

import { useRouter } from 'next/router';

function Search(props) {
  const router = useRouter();

  // Get the query parameter from the URL
  const { keyword1, keyword2 } = router.query;

  return (
    <div>
      The Search Keyword {keyword1} {keyword2}.
    </div>
  );
}

export default Search;

Next, we can see the option how to get the query params using getServerSideProps function

How to Get Query Parameters In a getServerSideProps

Using getServerSideProps function in Next.js we can generate server-side rendered pages, also it receives a context object as an argument, which contains a query property that holds the query parameters for that page.

We can access the query parameters by accessing the context value below.

export async function getServerSideProps({ context }) {
// context value contains the query params
const param = context.paramName;
}

If we want to access multiple query parameters, we can access them like the one below.

export async function getServerSideProps({ context }) {
const queryparam1 = context.param1;
const queryparam2 = context.param2;
const queryparam3 = context.param3;
}

Accessing Query Params In API Routes

We can also access query params by API route, we will get the req object property by destructuring the request object we can access the query params.

Here’s an example to access the query params in the API routes

import { NextApiRequest, NextApiResponse } from 'next';

export default (req: NextApiRequest, res: NextApiResponse) => {
const { query } = req;
const queryParams = query.paramName;

res.status(200).json({ queryParams });
};

Conclusion:

So there are three methods we can access the query params in NextJS

  1. In the component, we can useRouter() hook to access query parameters.
  2. In a server-side rendered page using getServerSideProps, we can access query parameters by destructuring the query property from the context.
  3. In an API route, we can access query parameters by destructuring the query property from the req object.

☞ Check out Next.js & React – The Complete Guide (incl. Two Paths!) (Buy now, offer ends in a few hours)

Filed Under: javascript, NextJS Tagged With: javascript, nextjs

Recent Posts

  • How to Generate random numbers in JavaScript
  • How to Scroll to an Element in a React Component?
  • How to get a Date without the Time in JavaScript
  • How to modify url without reloading the page using javascript
  • How to disable server side rendering in nextjs
  • How to get a file type from URL in JavaScript

Recent Posts

  • How to Generate random numbers in JavaScript
  • How to Scroll to an Element in a React Component?
  • How to get a Date without the Time in JavaScript
  • How to modify url without reloading the page using javascript
  • How to disable server side rendering in nextjs
  • How to get a file type from URL in JavaScript

Recent Comments

    Tags

    beginner colon cross-platform es6 function html ionic iOS javascript mobile application development nextjs objective-c swift switch ternary typescript uiwebview Visual Studio plugin web developer

    Copyright © 2025 Source Freeze