Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js | Is there any way to render an .xml file?

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:

  • example.com/help -> help.js
  • example.com/info -> info.js

So, is there any way to achieve this by avoiding accessing the backend?

like image 456
CoronelV Avatar asked Nov 20 '20 21:11

CoronelV


People also ask

What is XML render?

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.

Can you use XML with JavaScript?

With a few lines of JavaScript code, you can read an XML file and update the data content of any HTML page.

Can browser render XML?

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.

How display XML data in react?

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.


2 Answers

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

like image 60
Emanuel Avatar answered Oct 20 '22 11:10

Emanuel


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

like image 42
Israel Kouperman Avatar answered Oct 20 '22 13:10

Israel Kouperman