npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2020 – Pkg Stats / Ryan Hefner

contentful-sitemap

v1.0.15

Published

Easily generate a sitemap.xml file that consists of both static routes and dynamic routes generated from Contentful content.

Downloads

1,886

Readme

🗺 contentful-sitemap

npm NPM npm Coveralls github CircleCI Snyk Vulnerabilities for GitHub Repo

Dynamically generate an array of valid sitemap routes to enable building a live sitemap based on Contentful content via the Contentful API.

Install

Via npm

npm install contentful-sitemap

Via Yarn

yarn add contentful-sitemap

How to use

contentful-sitemap requires a Contentful client in order to fetch entries from your Contenful space in order to build your dynamic sitemap entries. So, make sure you have contentful as a dependency in your project.

Install contentful

npm i -S contentful

Create Contentful client

const contentful = require('contentful');
const { ContentfulSitemap } = require('contentful-sitemap');

const client = contentful.createClient({
  accessToken: '[ACCESS_TOKEN]',
  space: '[SPACE_ID]',
});

Next comes setting up the ContentfulSitemap instance that will be used by your /sitemap.xml route to generate and return the sitemap. ContentfulSitemap requires a client instance, so make sure you pass one into the constructor.

Create ContentfulSitemap instance

const sitemapGenerator = new ContentfulSitemap(client, [routes], {options});

Parameters

  • client - Contentful client that will be used for fetching locales and entries from Contentful.

  • routes - Array of route definitions to use to generate sitemap.

  • options - Options that you can use to customize how sitemaps are generated.

Routes

contentful-sitemap generates a route array that is compatible with the sitemap package for generating your sitemap.xml file, so all route options supported by that package are also supported within the routes array you pass in. You can pass in both static and dynamic Contentful routes within the array. Below are the few specifics that directly relate to how contentful-sitemap will process your routes entries.

NameDefaultDescription
urlnullUse this property if the path you are providing does not require any segments to be swapped out dynamically.
idnullContentful entry id to fetch for the specific path. Only used if the dynamicLastmod option is set to true.
patternnullpath-to-regexp pattern to use for generating dynamic listings based on Contentful content or setting locale specific paths.
priority1Default priority to set for each url. Set to 1 as a default so it can be excluded in your routes definitions.
paramsnullObject used to specify the mapping of pattern parameter to Contentful response data.
querynullQuery used by the Contentful client for fetching entries. All contentful getEntries query options are supported.

Default Options

The following options can be used to customize the way your sitemap is generated. The one option that you’ll definitely want to set, if not defined in your routes is the origin option, which is prefixed before the urls and patterns defined in your routes.

NameDefaultDescription
locales[]Array of locales to include for all route instances, if not using dynamicLocales.
dynamicLocalesfalseWhether or not to fetch the list of enabled locales from Contentful.
dynamicLastmodfalseAutomatically use the lastmodParam value of each entry to set the lastmod value.
lastmodParamsys.updatedAtContentful model field to use when populating lastmodISO in route(s).
localeParamlocaleThe param to set within your pattern to replace with a locale.
defaultLocalenullThe default locale that will be used in the main loc value for a url.

Methods

  • addRoute(route) - Method to use for adding additional urls after the initial ContentfulSitemap instance has been created.

  • buildRoutes() - The magic✨ Call this method when you want to generate your Contentful routes to be passed to sitemap.

  • toXML((xml, err) => {}) - DEPRECATED - This was the previous method that this class used to build and return the full sitemap.xml string, but due to changes made to the sitemap package it seemed like it would be easier to support the current—and future—versions of that package by simplifying this package to do one thing well, while offering more flexibility with how you would like to use sitemap to generate your sitemap(s).

Example

const express = require('express');
const contentful = require('contentful');
const { SitemapStream, streamToPromise } = require('sitemap');
const { createGzip } = require('zlib');
const { ContentfulSitemap } = require('contentful-sitemap');

const app = express();

const client = contentful.createClient({
  accessToken: '[ACCESS_TOKEN]',
  space: '[SPACE_ID]',
});

const sitemapGenerator = new ContentfulSitemap(client, [
  {
    pattern: '/',
    id: '[HOME_PAGE_ID]',
  },
  {
    pattern: '/about',
    id: '[ABOUT_PAGE_ID]',
    priority: 0.7,
  },
  {
    pattern: '/news',
    id: '[NEWS_PAGE_ID]',
  },
  {
    pattern: '/news/:slug',
    priority: 0.5,
    query: {
      content_type: '[CONTENTFUL_MODEL_TYPE (e.g. `newsArticlePage`)]',
      select: 'fields.slug',
    },
    params: {
      slug: 'fields.slug',
    },
  },
  {
    url: '/terms',
    priority: 0.3,
  },
  {
    url: '/privacy',
    priority: 0.3,
  }
]);

let sitemap;

app.get('/sitemap.xml', (req, res) => {
  res.header('Content-Type', 'application/xml');
  res.header('Content-Encoding', 'gzip');

  if (sitemap) {
    return res.send(sitemap);
  }

  try {
    const smStream = new SitemapStream({ hostname: 'https://example.com/' });
    const pipeline = smStream.pipe(createGzip());

    return sitemapGenerator.buildRoutes()
      .then(routes => {
        // pipe your entries or directly write them.
        routes.forEach(route => smStream.write(route));
        smStream.end()

        // cache the response
        streamToPromise(pipeline).then(sm => sitemap = sm)
        // stream write the response
        pipeline.pipe(res).on('error', (e) => {throw e})
      })
      .catch(error => {
        console.error(error);
        res.status(500).end();
      });
  } catch (e) {
    console.error(e)
    res.status(500).end()
  }
});

...

License

MIT © Ryan Hefner