Skip to content

Instantly share code, notes, and snippets.

@a-barbieri
Forked from edolyne/server.js
Created July 13, 2020 15:10
Show Gist options
  • Save a-barbieri/d9a229c1adc9b7e2d876398b5e8e8418 to your computer and use it in GitHub Desktop.
Save a-barbieri/d9a229c1adc9b7e2d876398b5e8e8418 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}`)
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment