Home > References > Web Development > Nextjs references

Next js quick references and tips

Last updated : March 18, 2021

In this tutorial, we will discuss some features in Nextjs that can make our development less complicated. You will find use cases of these features at any point of your Nextjs project development phase.

How to use Nextjs env local variables

Shared values throughout the application such as api URLs, resource locations can reside in an environment variable file named .env.local. The .env.local file resides on the application root, the same level as the package.json file.

API_URL=https://www.exampleapi.com/saveUser

The above entry in the .env.local will make the API_URL available to the server-side rendered portion of the component. In other words, the API_URL is available in the Node js environment, not in the browser. The API_URL is accessible by prepending process.env to the variable name.

export async function getServerSideProps({ params }) {
const response = await fetch(process.env.API_URL);
//..........
}

If you need to access environmental variables on the client-side or browser, you need to prepend NEXT_PUBLIC_ to the variable name. Prepending NEXT_PUBLIC_ will make the variable accessible from the server-side as well as the client-side.

NEXT_PUBLIC_API_URL=https://www.exampleapi.com/showUser
useEffect(() => {
 fetch(process.env.NEXT_PUBLIC_API_URL)
   .then(res => res.json())
   .then(data => {
       setUser(data);
   })
}, []);

How to change Nextjs default server port

The default server port doesn't always have to be port 3000. You can change it in the package.json file. Don't forget to restart the node server. Change "dev" and "start" scripts as below. Replace 3001 with your choice of the port number.

"dev": "next dev -p 3001",
"build": "next build",
"start": "next start -p 3001"

How to add javascript dynamically to a page

Loading resources cost resources, especially in mobile devices. Therefore, simply if you don't use it, don't load it on the page. There are several ways to achieve this.

The below is the basic code to insert a script. Make sure this script is in the head section of the page.

<script dangerouslySetInnerHTML={{ __html: `function dynamicjs(){alert('Load only when you need this js')}` }}></script>

Loading a javascript from the database

You can conditionally load a javascript based on specific logic. Your javascript code can reside in the database or an environment variable. The below code will render it on the page.

{props.isJsNeeded && <script dangerouslySetInnerHTML={{ __html: props.jsCode }}></script>}

Loading a javascript from a file

This is how you load a javascript file conditionally.

{props.isJsNeeded && <script async={true} src={props.pathToJsFile}></script>}

How to add Nextjs title and meta description

One of the significant factors to use Next js is to make your React js application SEO friendly. Therefore, the page title and the meta description are things we cannot overlook. In Next js, we use the next/head to enclose the title and meta description. All you have to do is overriding the title and meta description in each page component. Doing this will not duplicate the title and meta descriptions.

import Head from 'next/head'
const Post = ({props}) => {
return <div>
  <Head>
      <title>{props.pageTitle}</title>
      <meta name="description" content={props.metadescription} />
  </Head>
//rest of the code goes here
}

How to re-render or refresh a Nextjs page

Unlike in client-side rendering, a server-side rendered page doesn't know that the underlying data has changed. The reason is the underlying data is immutable once the page is server-rendered. Therefore, any updates to page data will not reflect on the page unless the page is refreshed. Here is how you can overcome that issue. All you have to do is calling the refreshPage function after any updates.

import { useRouter } from 'next/router';
function Post(props) {
  const router = useRouter();
  //Method to call after prop changes
  const refreshPage = () => {
    router.replace(router.asPath);
  }
}
export async function getServerSideProps(context) {
  // API logic here
}

How to use react-avatar in Nextjs

React avatar allows you to generate an avatar based on the information you have about an entity. I have included some additional code to style your avatar in different colors.

import Avatar from 'react-avatar';
const Forum = (props) => {
    const colours = ['blue', 'green', 'orange', 'purple', 'red'];
    const getColour = () => colours[Math.floor(Math.random() * colours.length)];
    return (
        <Avatar color={getColour()} name={user.name} size="50" round={true} />
    );
}

The generated avatar would look like below.

React avatar in action
Figure 1 : React avatar in action
Lance
By: Lance
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Leave a comment

No Comments