Created
August 6, 2018 15:24
-
-
Save edolyne/10bf9cfdd1e75557c3c4c63a2c1fc0b5 to your computer and use it in GitHub Desktop.
Dynamic Sitemap creation for NextJS based projects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Thanks a lot!
Implemented myself with a few modifications like using
graphql-request
. Works perfectly!