Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@edolyne
Created August 6, 2018 15:24
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save edolyne/10bf9cfdd1e75557c3c4c63a2c1fc0b5 to your computer and use it in GitHub Desktop.
Save edolyne/10bf9cfdd1e75557c3c4c63a2c1fc0b5 to your computer and use it in GitHub Desktop.
Dynamic Sitemap creation for NextJS based projects
const express = require('express');
const next = require('next');
const sm = require('sitemap');
const axios = require('axios');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const determinePriority = (url) => {
if (url.includes('buy/')) {
return 0.6
} else if (url.includes('blog/')) {
return 0.8
} else {
return 1.0
}
};
const createSitemap = (res) => {
let urlRoutes = [];
let sitemap = sm.createSitemap ({
hostname: 'base url of site',
cacheTime: 60
});
axios.get('rest endpoint of dynamic page slugs')
.then(function(response) {
urlRoutes = [...urlRoutes, ...response.data]
urlRoutes.map((item) => {
sitemap.add({
url: item,
changefreq: 'daily',
priority: determinePriority(item)
})
})
res.send( sitemap.toString() )
});
};
app.prepare()
.then(() => {
const server = express();
server.get('/sitemap.xml', function(req, res) {
res.header('Content-Type', 'application/xml');
createSitemap(res);
});
server.get('/:slug', (req, res) => {
const actualPage = '/page'
const queryParams = { slug: req.params.slug }
return app.render(req, res, actualPage, queryParams)
});
server.get('/', (req, res) => {
const actualPage = '/page'
const queryParams = { slug: 'homepage', modal: req.params.modal }
return app.render(req, res, actualPage, queryParams)
});
server.get('*', (req, res) => {
const pathname = req.originalUrl.substr(1);
return handle(req, res)
});
server.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
});
});
@dlbnco
Copy link

dlbnco commented Apr 6, 2019

Thanks a lot!

Implemented myself with a few modifications like using graphql-request. Works perfectly!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment