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 Next js env local variables
Shared values throughout the application, such as API URLs, and resource locations, can reside in an environment variable file named .env.local
.
The .env.local
file resides on the application root at 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 must prepend NEXT_PUBLIC_
to the variable name.
Prepending NEXT_PUBLIC_
will make the variable accessible from the server and client sides.
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 Next js 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 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 on mobile devices. Therefore, simply if you don't use it, don't load it on the page. There are several ways to achieve this.
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
That is how you load a javascript file conditionally.
{props.isJsNeeded && <script async={true} src={props.pathToJsFile}></script>}
How to add Next js title and meta description
One of the significant factors to using 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 override each page component's title and meta description. Doing this will not duplicate the title and meta descriptions.
*Overriding the HEAD
does not work in Next Js version 12+. The outermost HEAD
will override all the nested HEADS
.
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 Next js 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 call 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 Next js
React avatar allows you to generate an avatar based on your information 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 the one below.