🕶 Working with Metadata+v0.5

Want to add some metadata to your page? Now you can with the Head API! All page templates have access to this API

Using the Head API

Using static metadata

You can access the head property in the layout template
    
      module.exports = ({ title, content, head, dev }) => `
        <!DOCTYPE html>
        <html>
          <head>
            ${head}
            <script src="${dev ? 'https://dev.script.js' : 'https://prod.script.js'}"></script>
            <title>${title}</title>
          </head>
          <body>
            ${content}
          </body>
        </html>
      `;
    
  
In your page template you can export the head function
    
      const page = ({ data, dev }) => `
        <p>${data.text}</p>
      `;

      module.exports = {
        layout: 'default',
        title: 'Hydrogen webpage',
        page,
        data: () => ({
          text: 'Hydrogen metadata',
        }),
        head: () => [
          ['meta', { name: 'description', content: 'Hydrogen metadata' }],
        ];
      };
    
  
Run build command
    
      <!DOCTYPE html>
      <html>
        <head>
          <meta name="description" content="Hydrogen metadata" />
          <script src="https://dev.script.js"></script>
          <title>Hydrogen webpage</title>
        </head>
        <body>
          <p>Hydrogen metadata</p>
        </body>
      </html>
    
  

Using asynchronous data with the Head API

We also have access to the data from the Data API

    
      const axios = require('axios');

      const page = ({ data, dev }) => `
        <p>This project has ${data.likes} likes</p>
      `;

      module.exports = {
        layout: 'default',
        title: 'Hydrogen webpage',
        page,
        data: async ({ dev }) => ({
          likes: await axios.get('https://likes.com').then(res => res.data),
        }),
        head: ({ likes, dev }) => [
          ['meta', { name: 'og:likes', content: likes }],
        ];
      };
    
  

Using the Hydrogen config with the Head API

With the global name property provided by the Hydrogen Config, we can use it to manage our page title's

    
      const page = () => `
        <p>The head will be injected into the layout</p>
      `;

      module.exports = {
        layout: 'default',
        page,
        head: ({ config }) => [
          ['title', {}, `Head API | ${config.name}`]
        ];
      };
    
  

What if you want to update your static assets folder, you can do that to!

    
      const page = () => `
        <p>The head will be injected into the layout</p>
      `;

      module.exports = {
        layout: 'default',
        page,
        head: ({ config }) => [
          ['script', { src: `/${config.staticFolder}/js/script.js` }, true]
        ];
      };