I'm trying to render an XML file when pointing to www.example.com/sitemap.xml. Since the project was developed using Next.js, the routing works with the js files stored in the pages directory:
So, is there any way to achieve this by avoiding accessing the backend?
Render XML is a synchronous activity that takes an instance of an XML schema element and renders it as a stream of bytes containing XML or an XML string.
With a few lines of JavaScript code, you can read an XML file and update the data content of any HTML page.
The most popular web browsers can display and process XML natively. Nowadays, it's just a matter of opening a file. XML is now mature enough that recent versions of the more popular web browsers support it natively.
Before beginning the React app guide, you must have XML data to show, which you may need to collect from the server. To fetch the data from the server, use the HttpClient Axios, whichis installed using the below npm command. Now that you have installed Axios, create a new component, for example, ParseXml.
JS Version
/pages/sitemap.xml.jsx
import React from 'react'
class Sitemap extends React.Component {
static async getInitialProps({ res }) {
res.setHeader('Content-Type', 'text/xml')
res.write(`<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
...
</urlset>`)
res.end()
}
}
export default Sitemap
TS Version
/pages/sitemap.xml.tsx
import { GetServerSideProps } from 'next'
import React from 'react'
const Sitemap: React.FC = () => null
export const getServerSideProps: GetServerSideProps = async ({ res }) => {
if (res) {
res.setHeader('Content-Type', 'text/xml')
res.write(`<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
</urlset>`)
res.end()
}
return {
props: {},
}
}
export default Sitemap
:D
Add a static file called sitemap.xml under public directory
public/sitemap.xml
after build you can access www.yourdomain.com/sitemap.xml
Read more on static files: https://nextjs.org/docs/basic-features/static-file-serving
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With