This content originally appeared on DEV Community and was authored by Burhan Haroon
According to google.com
A sitemap is a file where you provide information about the pages, videos, and other files on your site, and the relationships between them. Search engines like Google read this file to crawl your site more efficiently.
First of all we are going to need the help of this very powerful package named Remix SEO. So, install it by using the following command.
npm i @balavishnuvj/remix-seo
Then make a new file named sitemapRoutes.server.ts
within our app/ directory. After creating the file paste the following code there.
import type { EntryContext } from "@remix-run/node";
import { generateSitemap } from "@balavishnuvj/remix-seo";
const siteUrl =
process.env.ENVIRONMENT === "production"
? "https://yourProductionWebsiteUrl.com"
: "http://localhost:3000";
type Handler = (
request: Request,
remixContext: EntryContext
) => Promise<Response | null> | null;
export const otherRootRoutes: Record<string, Handler> = {
"/sitemap.xml": async (request, remixContext) => {
return generateSitemap(request, remixContext, {
siteUrl,
});
},
};
export const otherRootRouteHandlers: Array<Handler> = [
...Object.entries(otherRootRoutes).map(([path, handler]) => {
return (request: Request, remixContext: EntryContext) => {
if (new URL(request.url).pathname !== path) return null;
return handler(request, remixContext);
};
}),
];
That's it for the sitemapRoutes.server.ts
file. Now head to the entry.server.tsx
file in the app/ directory and make the following changes there:
import type { EntryContext } from "@remix-run/node";
import { RemixServer } from "@remix-run/react";
import { renderToString } from "react-dom/server";
+ import { otherRootRouteHandlers } from "./sitemapRoutes.server";
- export default function handleRequest(
+ export default async function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext
) {
+ for (const handler of otherRootRouteHandlers) {
+ const otherRouteResponse = await handler(request, remixContext);
+ if (otherRouteResponse) return otherRouteResponse;
+ }
const markup = renderToString(
<RemixServer context={remixContext} url={request.url} />
);
responseHeaders.set("Content-Type", "text/html");
return new Response("<!DOCTYPE html>" + markup, {
status: responseStatusCode,
headers: responseHeaders,
});
}
and now you're done! Congratulations you did it ;)
Now you just have to goto http://localhost:3000/sitemap.xml
link and you'll see the sitemap generated like this:
This content originally appeared on DEV Community and was authored by Burhan Haroon
Burhan Haroon | Sciencx (2022-07-20T11:26:24+00:00) How to generate /sitemap.xml route in Remix framework. Retrieved from https://www.scien.cx/2022/07/20/how-to-generate-sitemap-xml-route-in-remix-framework/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.