質問
setup sitemap
Update: 

Introduce

A sitemap is a file where you provide information about the pages, videos, and other files on your site, and the relationships between them.

Setup

First, you need a library to build xml file, here is xmlbuilder:

yarn add xmlbuilder

Import it inside your sitemap.tsx;

import * as builder from 'xmlbuilder';

Then you need to define a list of pages:

const staticPages = [
  {
    modifiedAt: '2019-12-23',
    path: '/promotion/posting',
  },
] as TPage[];

or you can import a list from another place in your source:

import { getPostList } from '~/utils/getPostList';

After that, define an object of Sitemap like this:

Sitemap.getInitialProps = async ({ res }) => {
try {
	const feedObject = {
	urlset: {
		'@xmlns': 'http://www.sitemaps.org/schemas/sitemap/0.9',
		'@xmlns:image': 'http://www.google.com/schemas/sitemap-image/1.1',
		url: [],
	},
	};

push your listpage to url of this object.

Then, call builder to create sitemap:

const sitemap = builder.create(feedObject, { encoding: 'utf-8' });

The rest is handle your sitemap:

if (res) {
	res.setHeader('Cache-Control', 's-maxage=5, stale-while-revalidate');
	res.setHeader('Content-Type', 'application/xml');
	res.statusCode = 200;
	res.end(sitemap.end({ pretty: true }));
	}

	return;
} catch (error) {
	return { error: 404 };
}

Remember to export your function.

Finally, run yarn build to automatic create sitemap.

Try to access /sitemap to see your result.

There're some others library for you to create sitemap, you can choose properly one for your application.

If you have any confusion about this, be free to left a question here.

この記事が気に入ったら応援お願いします🙏
2
ツイート
LINE
Developer
Price Rank Dev
I use Next.js (React) and Firebase (Firestore / Auth) for development. We are also developing APIs for Ruby on Rails and GraphQL. Our team members are 6 Vietnamese and Japanese engineers.