Serve Static Files sitemap.xml, robots.txt and favicon.ico With Next.js

Serve static files sitemap.xml, robots.txt and favicon.ico with Next.js

Well, to serve static files such as sitemap.xml, robots.txt and favicon.ico with Next.js you just put those static files in static folder and add the below code to your server (server.js) config:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const robotsOptions = {
  root: __dirname + '/static/',
  headers: {
    'Content-Type': 'text/plain;charset=UTF-8',
  }
};
server.get('/robots.txt', (req, res) => (
  res.status(200).sendFile('robots.txt', robotsOptions)
));

const sitemapOptions = {
  root: __dirname + '/static/',
  headers: {
    'Content-Type': 'text/xml;charset=UTF-8',
  }
};
server.get('/sitemap.xml', (req, res) => (
  res.status(200).sendFile('sitemap.xml', sitemapOptions)
));

const faviconOptions = {
  root: __dirname + '/static/'
};
server.get('/favicon.ico', (req, res) => (
  res.status(200).sendFile('favicon.ico', faviconOptions)
));

So far so good, That’s it!!! See ya!!! :)