Issues with NuxtJs dynamic open graph tags are causing errors

i am currently working on implementing dynamic open graph meta tags using this code snippet

    async asyncData({ app, route }) {
        let postDetails = await app.$axios.get(`/api/v1/news/single/${route.params.id}`);
        postDetails = postDetails.data.post;
        return { postDetails };
    },
    head() {
        return {
             meta: [
                { hid: 'title', name: "title", content: this.postDetails.title },
                { hid: "description", name: "description", content: this.postDetails.body },
                { hid: "twitter:image", name: "twitter:image", content: this.postDetails.image },
                { hid: "twitter:card", name: "twitter:card", content: "summary_large_image" },
                { hid: "og:image",name: "og:image", content: this.postDetails.image },
                { hid: "og:image:secure_url", name: "og:image:secure_url", content: this.postDetails.image },
                { hid: "og:title", name: "og:title", content: this.postDetails.title },
                { hid: "og:description", name: "og:description", content: this.postDetails.body },
                { hid: "description", name: "description", content: this.postDetails.body },
                { hid: "og:url", name: "og:url", content: window.location.href }
            ]
        };
    },

After checking the logged postDetails in the asyncData function and seeing that the data is present, I noticed that when I open the page and inspect it, the meta tags are correctly updated. However, when I try to share the link on Facebook or view the HTML source code, only the default open graph tags are displayed. What could be the issue here? Any help would be greatly appreciated.

Answer №1

After experimenting with numerous approaches, none of which were successful, I finally discovered a workaround for manipulating meta tags by injecting them directly into the app object within the asyncData function. Surprisingly, this method proved to be highly effective, resolving all issues encountered along the way. Even attempts to manually integrate vue-meta failed to deliver the desired outcome.

async asyncData({ app, route }) {
        let postDetails = await app.$axios.get(`/api/v1/news/single/${route.params.id}`);
        postDetails = postDetails.data.post;
        const mutation = app.head.meta.map(i => {
            if(i && i.hid){
                // Modify meta tag content based on specific criteria
            }
            return i;
        });
      app.head.meta = mutation;
      return { postDetails };
},

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

Deciphering JSON data retrieved from a RESTful server

My goal is to create a graph from a table using Google's graph API. Upon loading the page, it retrieves JSON data from my REST server with this JavaScript function. No errors are shown in the JavaScript console. $(document).ready(function() { ...

Invoking a function from a separate JavaScript file and finding out that an object is considered null

The source code for a word game is stored in Main.js file. Currently, I am attempting to introduce another file called Bookmarks.js (included on the web page prior to the Main.js file). This new file will contain an object var bookmarks = {}; that stays s ...

After submitting a form in Reactjs, the input fields are not resetting

As a newcomer to Reactjs, I recently embarked on building two-way binding forms in React. Upon coding a form, my intention was for the form to clear after submission. However, even after submission, the form remains uncleared. Can someone please identify t ...

Enhance your Highmap R or JavaScript visualization with a unique custom legend feature

Provided below is my code snippet, output$map <- renderHighchart({ region_map = hcmap("countries/nz/nz-all") highchart(type = "map") %>% hc_title(text = "Average") %>% hc_add_series_map(map = region_map, df = data1, joinBy = " ...

Determine the height of a DIV element and its contents using JQuery

In this div, there are various elements present: <div class="menuItem designMenu" id="dMenu"> <ul class="menuList menu"> <li class="menuHeader">Design</li> <li class="projectHeader">Mother</li> <li clas ...

A snippet of jQuery programming that enables automatic transitions between images

Trying to figure out how to achieve this - I want an image to change every 3 seconds using jquery. Can anyone help me with this? Unfortunately, I haven't been able to find any resources on this specific topic. ...

My goal is to develop a program that generates a tree structure from an array of objects

I am looking to transform an array of objects by renaming specific keys and removing certain key-value pairs at each level. Here is the initial input: { "node": [ { "nodeName": "Clothes", "nodePath&qu ...

The background color of the Bootstrap 5 navbar remains static and does not transition when scrolling

I'm currently developing an Angular application using Bootstrap 5. One of the features I am working on is a transparent navbar that should change to a dark color when the page is scrolled. However, I seem to be encountering an issue where the navbar r ...

Handlers for event(s) not triggering on video element

In my NextJS application, I have implemented a feature to display a video file using the video element. I have added multiple event handlers to the video element: <video className='video-player' controls={true} preload='metadata&apo ...

The API call for /api/users/create was resolved without a response, which could potentially lead to requests getting stuck. This issue was detected in

I've developed an API endpoint to manage user account creation within my Next.js application, utilizing knex.js for handling queries. Despite this, I keep encountering the following error: API resolved without sending a response for /api/users/create ...

It is possible to retrieve a variable from a secondary table within an API on a list page, but it is not possible to do

The functionality of this page, which reads and displays a full table from an API, is working flawlessly; <template> <b-col> <h2> Enrolments <b-button :to="{ name: 'createEnrolment&apos ...

Utilize nested functions in Cypress instead of relying solely on a while loop

While working with Cypress, I noticed that using a while loop caused some issues. Instead of the while loop, I came up with this alternative solution: const functionName = () => { if ( a != b ) { this.functionName(); } else { cy.get(".sel ...

Capturing an image of an HTML5 canvas that includes an image object: tips and tricks

After creating a canvas and adding various objects like images, clipart, and text to it, I encountered an issue. When capturing a snapshot of the canvas with only text using the method `canvas.toDataURL()`, the snap is correct. However, when I include an i ...

Firefox displays an error when using jQuery.load(), but Chrome functions properly without any issues

I have created a function that opens a page in a dialog box instead of the main window. The code has been cleaned up and here is the revised version: var baseUrl = window.location.origin + '/static/docs/'; function handleLinkClick(event) { ev ...

Retrieve the HTML source code using AngularJS through an HTTP GET request

I came across a thread in the forum discussing a similar issue but unfortunately, it didn't have any answers. Let me explain my problem - I'm trying to validate a form using AngularJS and connect it by sending an HTTP request on submit. In my log ...

I am looking to convert a jsp table of search results into an MS-Excel file in the '.xlsx' format

(Edited) Let me clarify this situation further. I have a search page that allows users to look for employees based on various criteria. However, due to unexpected changes in the QA stage, I now need to add an export button that will save the filtered list ...

Can you explain the distinction between Mongoose's Delete and the Express app.delete function?

As I dive into learning NodeJS and utilizing MongoDB with mongoose, I've come across an interesting comparison. The course I'm currently enrolled in focuses on using mongoose methods for "Delete" and "Update" operations, implementing Express to h ...

Identifying a web application functioning as a homescreen app within the Android Stock Browser

We are in the process of developing a web application that needs to function as a standalone or homescreen app. While we can identify if it is being accessed from Chrome or Safari using window.navigator.standalone or window.matchMedia('(display-mode: ...

How to automatically insert a comma into numbers as you type in Vue.js

I am trying to insert separators in my numbers as I type, but for some reason it is not working. Sample Code <el-input-number v-model="form.qty" style="width: 100%;" id="test" placeholder="Quantity" controls-position="right" v-on:keyup="handleChange" ...

When making an API request, the response includes the body of the data, however, the specific properties cannot be

I've encountered an unusual bug while using the Mapbox geocoding API. const geocode = async (address, callback) => { const url = `https://api.mapbox.com/geocoding/v5/mapbox.places/${address}.json?access_token=token&limit=1` try { ...