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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@moxy/next-sitemaps

v3.3.0

Published

Library to generate sitemaps in a next application

Downloads

28

Readme

next-sitemaps

NPM version Downloads Build Status Coverage Status Dependency status Dev Dependency status

This module provides an API handler and a plugin that enables your Next.js application to have working sitemaps so that search engine crawlers can index all your pages.

Installation

npm install @moxy/next-sitemaps

Usage

1. Add the plugin to next.config.js

const withSitemap = require('@moxy/next-sitemaps/plugin');

module.exports = (phase) => withSitemap(phase, 'https://moxy.studio')({ ...nextConfig });

ℹ️ If you have multiple plugins, you may simply compose them or use next-compose-plugins for better readability.

2. Add the API handler on pages/api/sitemap.xml.js

import createSitemapApiHandler from '@moxy/next-sitemaps';

export default createSitemapApiHandler({
    mapDynamicRoutes: {
        '/[id]': () => ['id1', 'id2'],
    },
});

3. Add robots.txt file

Sitemap: ${siteUrl}/api/sitemap.xml

User-agent:*
Disallow:

# ...

Please note that ${siteUrl} will be replaced automatically by the siteUrl specified when instantiating the plugin. However, the replacement will not happen during development to avoid checking in the changed file into source-control (e.g.: git).

⚠️ During development, new pages will not be present in the XML. Restart the development server for page changes to take effect.

API

withSitemap(phase, siteUrl, [options])

The Next.js plugin that should be installed in next.config.js. It will do two things:

  • Iterate over the /pages (or src/pages) folder and map all files into routes. These mappings will be used by the API Handler.
  • Replace the ${siteUrl} placeholder inside robots.txt with siteUrl.

phase

Type: string

The Next.js current context phase. This plugin will only be active if phase is PHASE_DEVELOPMENT_SERVER or PHASE_PRODUCTION_BUILD.

siteUrl

Type: string
Default: '/'

The website URL.

options

Type: object

replaceSiteUrlInRobots

Type: boolean
Default: true if process.env.NODE_ENV is set to production

This option will replace ${siteUrl} inside robots.txt. During development, you want this option disabled to avoid checking in the resulting file into source-control (e.g.: git).

createSitemapApiHandler([options])

Defines an API handler that will respond with a valid sitemap XML file containing the website pages.

options

Type: object

mapDynamicRoutes

Type: object
Default: {}

An object that indicates the possible values for each dynamic route. More info.

cacheControl

Type: string
Default: public, max-age=3600 (max-age is set to 0 if not in production)

A string defining the Cache-Control header for HTTP responses. Since sitemaps can be rather expensive to generate, you may leverage a Reverse Proxy cache or a pull CDN such as CloudFlare (via a page rule), to cache the sitemap response.

While a reverse-proxy or pull CDN is preferable, you may cache the sitemap programmatically like so:

import pMemoize from 'p-memoize';
import createSitemapApiHandler from '@moxy/next-sitemaps';

const apiHandler = createSitemapApiHandler('https://moxy.studio', {
    mapDynamicRoutes: {
        '/[id]': () => ['id1', 'id2'],
    },
});

export default pMemoize(apiHandler, {
    cacheKey: () => 'sitemap',
    cachePromiseRejection: true,
    maxAge: 5 * 60 * 1000, // 5 minutes
});

The example above uses p-memoize, which caches the result in-memory for 5 minutes. However, you can use a distributed cache, such as Redis.

logWarning

Type: function
Default: see logWarningDefault in src/api-handler/index.js

A function to log possible warnings. It has the following signature: (message) => {}.

logError

Type: function
Default: see logErrorDefault in src/api-handler/index.js

A function to log possible errors. It has the following signature: (err) => {}.

Handling dynamic routing

createSitemapApiHandler('https://moxy.studio', {
    mapDynamicRoutes: {
        '/[project]': () => ['some-project', 'another-project'],
        '/old/[post]': () => ['old-post', 'ancient-post'],
        '/[post]/new': () => ['new-post', 'another-new-post'],
    },
});

The API route above would respond with the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>https://moxy.studio/another-project</loc>
    </url>
    <url>
        <loc>https://moxy.studio/some-project</loc>
    </url>
    <url>
        <loc>https://moxy.studio/old/old-post</loc>
    </url>
    <url>
        <loc>https://moxy.studio/old/ancient-post</loc>
    </url>
    <url>
        <loc>https://moxy.studio/new-post/new</loc>
    </url>
    <url>
        <loc>https://moxy.studio/another-new-post/new</loc>
    </url>
</urlset>

ℹ️ Catch all routes are also supported.

You might have routes with several dynamic placeholders. In this case, first-level mappers will be called first, second-level mappers will be called secondly, one time for each result of the first mapper, and so on. In short, calls to mappers are permuted and they receive the current iteration values to aid you in data-fetching.

createSitemapApiHandler('https://moxy.studio', {
    mapDynamicRoutes: {
        '/[company]': async () => {
            // Returns ['microsoft', 'apple']
            const companies = await fetchCompanies();

            return companies;
        },
        // The function below will be called two times.
        // The first will have `company` set microsoft and the second one will have it set to `apple`.
        '/[company]/[apps]': ({ company }) => {
            // Returns ['vscode', 'vsstudio'] for microsoft and returns ['itunes'] for apple.
            const apps = fetchCompanyApps(company);

            return apps;
        },
    },
});

Assuming the return values of the mappers above, the generated sitemap would look like:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>https://moxy.studio/apple</loc>
    </url>
    <url>
        <loc>https://moxy.studio/apple/itunes</loc>
    </url>
    <url>
        <loc>https://moxy.studio/microsoft</loc>
    </url>
    <url>
        <loc>https://moxy.studio/microsoft/vscode</loc>
    </url>
    <url>
        <loc>https://moxy.studio/microsoft/vsstudio</loc>
    </url>
</urlset>

Tests

$ npm t
$ npm t -- --watch  # To run watch mode

License

MIT License