Git Product home page Git Product logo

nuxt-seomatic-meta's Introduction

nuxt-seomatic-meta   NPM

Icon

If you're using Nuxt.js with Craft CMS headless then there's a good chance you'll be aiming for some decent SEO. A custom solution would take too much time, so a great alternative is to request the SEO data from SEOmatic via GraphQL.

This module grabs the SEOmatic data and converts it to a format that Nuxt.js expects in it's head property.

Getting started

Before starting, I'll assume you've installed Craft (>=3.3), SEOmatic (>=3.2.28) and enabled Crafts GraphQL API.

⚠️ Note: Craft can't be in headlessMode - Headless mode won't work with SEOmatic as we need to match the URI which gets turned off when headlessMode is enabled.

⚠️ Note: Within Craft > GraphQL > Schemas, be sure to adjust the scope to the right entries in the GraphQL schema - I find it easy to forget that.

  1. Install nuxt-seomatic-meta via yarn or npm:

    yarn add nuxt-seomatic-meta
    # or: npm install nuxt-seomatic-meta
  2. Add the seomatic-meta and axios plugins to your modules section in nuxt.config.js:

    /*
     ** Nuxt.js modules
     */
    modules: [
      'nuxt-seomatic-meta',
      '@nuxtjs/axios',
      // '@nuxtjs/dotenv',
    ],

    '@nuxtjs/axios': Axios is used to connect to the Craft CMS API - it's automatically installed as a dependency of nuxt-seomatic-meta so you'll just need to add it to the array.

    '@nuxtjs/dotenv' (optional): To specify your GraphQL connection variables in a .env file then install the nuxt dotenv module.

  3. Now specify the GraphQL connection settings - you have two options:

    a) Add the connection settings to an .env file in your project root (if you're using the @nuxtjs/dotenv module):

    # Craft installation url
    BACKEND_URL=https://YOUR_DOMAIN
    
    # GraphQL api path
    GRAPHQL_PATH=/api
    
    # GraphQL bearer token (Not required if API is public)
    GRAPHQL_TOKEN=ACCESS_TOKEN_SECRET

    b) Or add the connection settings to a new seomaticMeta object in nuxt.config.js:

    /*
     ** Seomatic meta config
     */
    seomaticMeta: {
      backendUrl: 'http://YOUR_DOMAIN',
      graphqlPath: '/api',
      graphqlToken: 'ACCESS_TOKEN_SECRET',
    },
  4. Lastly, add some code to start the API request and supply the result to Nuxt's head property. This is added to your pages in pages/*.vue:

    <script>
    export default {
      //...
    
      // Get Seomatic data from Craft by route
      async asyncData({ app, route }) {
        const siteId = 1 // For multi-site installs
        return {
          headData: await app.seomaticMeta(route, siteId)
        };
      },
    
      // Supply the data to the Nuxt head property
      head() {
        return this.headData;
      }
    };
    </script>

Configuration

Options can be supplied in a seomaticMeta object in nuxt.config.js:

seomaticMeta: {
  debug: true,
  routeRemap: [
    {
      path: '/',
      getFrom: 'homepage',
    },
    {
      path: 'another-route',
      getFrom: 'gets-meta-from-this-route-instead',
    },
  ],
  backendUrl: 'http://YOUR_DOMAIN',
  graphqlPath: '/api',
  graphqlToken: 'ACCESS_TOKEN_SECRET',
},
Name Type Default Description
debug boolean false Display the GraphQL data and other useful feedback in your console when using npm run generate.
routeRemap array [] Custom remapping of route data so you can grab the SEOmatic data from another page.
Eg: Your Nuxt homepage has a route of / but you want data from a page in Craft with a slug of homepage.
backendUrl string `` The url for your Craft installation.
This can also be defined in your .env under the key BACKEND_URL.
graphqlPath string `` The path to your GraphQL API.
This can also be defined in your .env under the key GRAPHQL_PATH.
graphqlToken string `` The token for your secured GraphQL endpoint.
This can also be defined in your .env under the key GRAPHQL_TOKEN.

Note: .env variables require the dotenv module.

🤝 Contributing

Contributions, issues and feature requests are welcome!
Feel free to check the issues page.

Show your support

Give a ⭐️ if this project helped you!

nuxt-seomatic-meta's People

Contributors

ben-rogerson avatar dependabot[bot] avatar wbrowar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

nuxt-seomatic-meta's Issues

Homepage data not shown

Hi Ben,

I've been working on a headless Nuxt website with CraftCMS and SEOMatic. Everything's working fine, except the homepage which is not loading the metadata. All other pages are fine.

Tried remapping the route in my nuxt.config.js as follows. Which does show the correct information in my console. However it does not seem to update the tags in the head.

seomaticMeta: { debug: true, backendUrl: process.env.BACKEND_URL, graphqlPath: process.env.GRAPHQL_PATH, graphQlToken: process.env.GRAPHQL_TOKEN, routeRemap: [ { path: '', getFrom: 'home', }, ], },

The slug of my homepage is 'home'. Also tried using '/' as the path, but that does not return the right data in the console.

This is my mixin which I load in my index.vue:

export default { name: "seoMatic", async asyncData({ app, route }) { const siteId = 1 // For multi-site installs return { headData: await app.seomaticMeta(route, siteId) }; }, // Supply the data to the Nuxt head property head() { return this.headData; }, }

These are my specs:

Package.json for my frontend:
Nuxt 2.15.8
nuxt-seomatic-meta 0.2.2

CraftCMS
craftcms/cms 4.2.1
nystudio107/craft-seomatic 4.0.9

I hope you can help. Thanks in advance.

Syntax Error: Unexpected token, expected ","

When adding nuxt-seomatic-meta to modules I get this unexpected token error which seems to be coming from the plugin chunk itself:

 ERROR  in ./.nuxt/lib.plugin.6ae22825.js                                                                                                                                   friendly-errors 16:45:59

Syntax Error: Unexpected token, expected "," (90:20)                                                                                                                        friendly-errors 16:45:59

  88 |       ? Object.values(metaTagContainer).reduce(
  89 |           {
> 90 |             if (next.name === 'description') {
     |                     ^
  91 |               // Override description tag with updated description
  92 |               next.hid = 'description';
  93 |             }

                                                                                                                                                                            friendly-errors 16:45:59
 @ ./.nuxt/index.js 32:0-92 379:25-63 385:19-57
 @ ./.nuxt/client.js
 @ multi ./node_modules/@nuxt/components/lib/installComponents.js eventsource-polyfill webpack-hot-middleware/client?reload=true&timeout=30000&ansiColors=&overlayStyles=&path=%2F__webpack_hmr%2Fclient&name=client ./.nuxt/client.js

This error does not occur when I remove nuxt-seomatic-meta from the modules.

Here is my modules setup:

  modules: [
    '@nuxtjs/apollo',
    '@nuxtjs/style-resources',
    'nuxt-i18n',
    '@nuxtjs/axios',
    'nuxt-seomatic-meta'

  ],

and here is the code I am using:

head() {
      return this.headData;
  },

  async asyncData (context) {
      const siteId = context.app.i18n.locale;
      return {
          headData: await context.app.seomaticMeta(context.route, siteId),
      }
  },

Tracking scripts not loading

First of all, thanks for creating this plugin! It's been super easy to integrate into our Nuxt/Craft setup.

I'm seeing an issue where tracking scripts don't seem to be running on page load/change. Had a quick look into the source code, and found that I think the trouble might be this line

innerHTML: JSON.stringify(script),

as (I believe) SEOmatic seems to return these scripts already in a string. Removing the extra stringifying so that the line becomes innerHTML: script seems to fix the issue.

Multisite not working with language in path

Hi,

I'm experiencing an issue with the multisite logic.

I’m using nuxt-i18n to manage the languages of my application. For a same page in two different languages, the URLs are like the following:

The issue is that, when I do have a /fr prefix in my route, that prefix is sent to SEOmatic via the uri parameter (see screenshot below), and because of this SEOmatic cannot find the related entry. Craft does not include the language in the URIs of the pages. When I remove this prefix manually, it works.

Screenshot 2020-04-02 at 10 19 17

This is what I did (in a simplified version) to make it work:

let fullPath = route.fullPath;

if (fullPath.startsWith('/fr')) {
     fullPath = route.fullPath.replace('/fr/', '/');
}

return await app.seomaticMeta({ fullPath }, siteId);

I guess we can agree this is not a sustainable solution. Is there a way (with the current methods/configuration elements) to indicate to the plugin the languages to remove from the path for all the pages? Would it be possible to implement that feature otherwise?

robots meta tag set to content="none"

Running live on a production server the robots meta tag stays set to content="none" even with Environment: live.
<meta data-n-head="ssr" content="none" name="robots">

Thank you!

Not an issue, just a shout out - this saved me sooo much time!
Thanks

Getting undefined from GraphQL

I tried setting this up, but for some reason all the requests come back with an undefined response. I rewrote the plugin to inject the function into the context so I could use it synchronously, and then it worked just fine.

inject('nuxtSeomaticMeta', (fullPath, id) => {
  //same code
});

So I'm wondering if there's something in the context of when the plugin is running? I've also logged out the actual query that's running, and putting that into a GraphQL client also returns the seomatic data.

Getting CORS errors on live site

We've set this up on a project and got it working locally (with the workaround mentioned in #4 )

But now that we've pushed the project to a live server we're just getting CORS errors. All our other graphql requests go through fine (using apollo), which leads me to think that there's got to be something in the way this is set up?

Nuxt 3

Is it possible to support nuxt 3

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.