Creating dynamic meta tags in Next.JS

I recently implemented dynamic meta tags for a specific page within my next.js application.

import CoinTossPage from '@/views/CoinTossPage';
import React, { useEffect, useState } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import axios from 'axios';

function CoinTossComponent() {
  const router = useRouter();
  const { id } = router.query;
  const [poolData, setPoolData] = useState(null);

  useEffect(() => {
    if (id) {
      fetchPoolData();
    }
  }, [id]);

  // fetch pool data from API using pool id
  const fetchPoolData = async () => {
    try {
      let config = {
        method: 'get',
        url: `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/gambling/coin-flip/pool/${id}`,
        headers: {
          Authorization: `Bearer ${process.env.NEXT_PUBLIC_API_KEY}`,
        },
      };
      const response = await axios(config);
      if (response.status === 200) {
        const payload = response.data.payload;
        if (payload) {
          setPoolData(payload);
        } else {
          setPoolData(null);
        }
      }
    } catch (error) {
      console.log('ERROR while fetching active pools from API ', error);
    }
  };

  return (
    <>
      <Head>
        <meta property="og:title" content={poolData?.tokenSymbol} />
        <meta property="og:image" content={poolData?.imageUrl} />
      </Head>
      <CoinTossPage />
    </>
  );
}

export default CoinTossComponent;

Upon inspection, the dynamic content appears properly in the meta tags. However, when sharing the page link, the image is not displaying as expected.

https://i.sstatic.net/O1v3U.png

This issue has left me puzzled. Any idea what might be causing this?

To troubleshoot, I referred to the documentation at https://nextjs.org/learn/seo/rendering-and-ranking/metadata and followed the instructions provided there.

Answer ā„–1

Big shoutout to all the amazing individuals who assisted me in resolving the issue mentioned above. Here is the updated and corrected code snippet:

import CoinTossPage from '@/views/CoinTossPage';
import React from 'react';
import Head from 'next/head';
import axios from 'axios';

function CoinTossComponent({poolData}) {
  return (
    <>
      <Head>
        <meta property="og:title" content={poolData?.tokenSymbol} />
        <meta property="og:image" content={poolData?.imageUrl} />
      </Head>
      <CoinTossPage />
    </>
  );
}

export async function getServerSideProps(context) {

  const { id } = context.query; // Access the route parameter

  let config = {
    method: 'get',
    url: `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/gambling/coin-flip/pool/${id}`,
    headers: {
      Authorization: `Bearer ${process.env.NEXT_PUBLIC_API_KEY}`,
    },
  };
  const response = await axios(config);
  const poolData = response.data.payload;

  // Return the data as props
  return {
    props: {
      poolData,
    },
  };
}

export default CoinTossComponent;

Answer ā„–2

When working with NextJS, it's important to understand that some parts of the HTML are rendered on the client side (for example in Google Chrome), while other parts are rendered on the frontend server. If metadata consumers can't see the metadata you see on the client, a few things may have happened:

  • The metadata consumer (like Twitter) sends a request to the frontend server.
  • The frontend server returns initial resources that don't need to be blocked. If elements within <Head> require processing on the client side, the frontend server may only return minimal data and instruct the client on how to continue loading until the intended state is reached.
  • The metadata consumer reads the minimal <Head> returned.
  • The client reconciles the state and fetches all required data to fill out the complete <Head>.

To address this issue, one solution is to fetch the necessary data for the <Head> on the server side. This can be achieved through methods like getStaticProps or getServerSideProps.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Order of AngularJS $q service response with error management

I am facing an issue with my function that handles asynchronous calls using promises in a sequence within a for loop. The problem is that the loop breaks when an exception occurs, but I need it to continue even after an exception is thrown. Here is my asy ...

Adjusting an SVG image element in real-time based on information retrieved from a mySQL database

Seeking to dynamically alter an SVG element based on data retrieved from a MySQL database. Imagine an SVG illustration in Adobe Illustrator featuring a table (rectangle) with 4 chairs (circles) around it. The goal is to represent each chair as a 'pe ...

The save and cancel button are experiencing technical difficulties and are currently non-functional

After creating an application in AngularJS to add and remove popup modals, I encountered an issue where the saved data was returning as undefined, and the cancel functionality was not working properly. Check out the JSFIDDLE here If anyone has any soluti ...

Tips for updating or deleting a ref value within the VueJS 3 composition api

I am utilizing a ref value in order to only trigger a click event when the ref value is changing. For instance, if I need to update/delete the array inside let myRef = ref([]);, should I simply access the proxy and carry out the operations like this : sel ...

Close overlay panel in PrimeFaces calendar

One of the components Iā€™m currently working with is an overlayPanel that contains a calendar. Here's a snippet of the code: <p:overlayPanel hideEffect="fade" showCloseIcon="true" dismissable="true" > <h:form> <p:p ...

the parameters receive an array

Currently, I'm facing a peculiar issue in my JavaScript project. I defined a custom event and passed an array to this event. $.publish("merilon/TablesLoaded", getTables()); The object that subscribed to this event did not receive the two parameters ...

Steps for checking if the specified row has been accurately filled out in a loop

Here is an example of how my JSON data is structured: { "main_object": { "id": "5", "getExerciseTitle": "TestFor", "language": "nl_NL", "application": "lettergrepen", "main_object": { "title": "TestFor", "language": "nl_NL", "exercises": [ { ...

A guide on effectively transferring Django lists/dictionaries to JavaScript

Looking to pass a list of items to a JavaScript array, using Django version 2.2.3. In my views.py: my_list = ["one", "two"] context = { 'my_list ': json.dumps(my_list), } return render(request, 'my_template.html', cont ...

Every time the attribute of the Angular controller changes, it is reinitialized

I'm currently in the process of developing a single page application using angularjs 1 and ngRoute, and I've encountered an issue. Within a view (/posts) I have a controller (PostsController) with an attribute called 'posts' that holds ...

When utilizing ASP.NET Core Razor pages for file uploads and utilizing AJAX Post to send the file to an IFormFile handler, the request

I have a straightforward task that involves uploading a file and using AJAX to post it to the Index page: <input type="file" id="file-selector" accept=".txt"> Here is the corresponding Javascript: const fileSelector ...

Adjusting the brightness of colors using JavaScript

I am looking for a way to return different color tones for a specific color using JavaScript. For example, if I have the color code #4a4a4a, I want to be able to return #494949 and #666464. If there is a package or method that can achieve this, please sugg ...

Troubleshooting: Issues with jQuery Dropdown Menu

I'm currently working on a website that includes a settings feature with a button. My goal is to have the options and other links display in a dropdown menu when hovered over. Although I have written what I believe to be the correct code, it's no ...

Receive the outcome once the form is submitted

Can someone provide quick assistance? I am looking to allow users to upload a CSV file for me to parse and analyze. Once the processing is done, I need to display the results back to the users. While uploading the file, I also need to ensure that the file ...

Searching for a specific value in a dropdown list during an iteration

Currently, I am iterating over an Ajax response to populate a JSON object in a select box. However, some of the JSON results may contain duplicate values. My goal is to check if a value already exists in the select box as I iterate through the loop. If a ...

Utilize three.js to blend colors in a 3D space

My 3d mesh consists of 11 static points with predefined values assigned to them. These points are represented as an array of positions in 3d space along with their corresponding values: x: 0.3 y: 0.4, z: 0.5, value: 100, x: 0.6 y: 0.9, z: 0.66, value: 20 ...

What is the process for activating `isActive` in a NextUI NavBaritem?

Question: I am currently delving into React and Next.js. I've decided to utilize NextUI components in crafting a NavBar. My goal is to implement a feature that highlights the active NavBarItem when clicked, indicating the current page. However, I&apo ...

How to execute a doPostBack function within a jQuery click event

My current situation involves a js function that triggers a click event on all 'a' elements... $(document).ready(function hideRanges() { $('a').click(function (event) { $('.ranges, #UpdatePanel').hide(); }); }); ...

Customizing the Header Navigation in Vue App.vue Across Various Views

Struggling to find the best approach for managing a header navigation in Vue 2 using Vuex with VueRouter. The main issue is creating a dynamic 'header' type navigation in App.vue. <div id="nav"> <!--Trying to create a dynamic ...

Steps to incorporate / insert Angular directive in an application

In my app, the main.js file is located in the root folder. -app |_ routes.js |_ main.js -components |_directives |_abc-directive.js I am trying to figure out how to define a directive that can be accessed from a different folder. This is what I at ...

Mongoose - facing issues with $and operator, looking for a way to locate an array containing both items

I'm currently developing a chat-based application that involves private messaging between individuals. Essentially, a Chat model in my application consists of the following schema: let schema = new Schema({ members: [{ type: ObjectId, ref: models.u ...