Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Meta for Nuxt.js

Can anyone help with a situation regarding meta info with dynamic data.

Problem

We are using Nuxt and generate our static page using npm run generate, and have identified several problems with this approach:

  • open graph and twitter meta tags can't be dynamically updated because crawlers don't run JS

  • details page during build process is generated only once and therefore doesn't have any relevant data until user has navigated to that page with URL parameters (e.g.
    example.com/cars/details?make=Audi&model=A6&carID=133852) which then feed AJAX GET request for data

Desired outcome

Open graphs, twitter and other meta tags unique for every car details page.

Question

Is it possible to achieve the desired outcome with generated static only? If not what would the process look like with SSR or server side generated meta content?

Our dist folder structure is currently:

dist/
  ├ index.html
  ├ cars/
    ├ index.html
    └ details/
      ├ index.html
      └ payment/
        └ index.html

cars page with a list of cars

details clicking a car navigates to details page of the selected car

payment car purchase page

like image 884
user10651574 Avatar asked Nov 14 '18 12:11

user10651574


1 Answers

No, it won't be possible to provide dynamic meta tags while serving pre-rendered static HTML.

Running Nuxt in universal mode makes it possible to fetch page data from API (via fetch, asyncData or nuxtServerInit action), generate HTML content of the page (including dynamic meta tags) and serve it to the user.

Simple usage example with SSR:

export default {
    async asyncData({ query, store }) {
        const { make, model, cardID } = query;
        // Validate query params

        // fetch data from API
        try {
            const carDetails = await store.dispatch('getCardInfo', {
                make,
                model,
                cardID,
            });
            return {
                cardDetails,
            };
        } catch (error) {
            // Redirect to error page or 404 depending on server response
        }
    },
    head() {
        return {
            title: this.carDetails.title,
            meta: [
                {
                    hid: 'og-title',
                    property: 'og:title',
                    content: this.carDetails.title,
                },
                // other meta
            ],
        };
    },
};

This will ensure that page data is loaded before component has been rendered and valid meta tags will be included for search engines consumption.

Sidenote: rather than using query params, you may want to check dynamic routes, which are significantly better for SEO, as well as user friendly URL (e.g. example.com/cars/audi/a6/133852)

like image 183
aBiscuit Avatar answered Oct 19 '22 00:10

aBiscuit