gatsby change page url

How to change page URL in Gatsby

If you are using Gatsby for building your website, you might come across a situation where you want to change the URL of a page. This could be due to various reasons, such as improving SEO or making the URL more user-friendly. Here are some ways to do it:

Option 1: Use Gatsby's createPage API

The first option is to use Gatsby's createPage API. This API allows you to programmatically create pages and customize their URLs. Here's how you can use it:


exports.createPages = async ({ actions }) => {
  const { createPage } = actions

  createPage({
    path: "/new-url",
    component: require.resolve("./src/templates/my-template.js"),
  })
}

In this example, we are creating a page with the URL "/new-url" and using a template called "my-template.js". You can replace these values with your own URL and template.

The second option is to use Gatsby's Link component. This component allows you to create links between pages in your website, and you can customize the URL using the "to" prop. Here's an example:


import { Link } from "gatsby"

const MyComponent = () => (
  Go to new URL
)

In this example, we are creating a link to the URL "/new-url". When the user clicks the link, they will be taken to the new URL.

Option 3: Use a redirect plugin

The third option is to use a redirect plugin. There are several Gatsby plugins available that allow you to redirect URLs. One popular plugin is "gatsby-plugin-meta-redirect". Here's how you can use it:

  1. Install the plugin: npm install gatsby-plugin-meta-redirect
  2. Add the plugin to your Gatsby config:

module.exports = {
  plugins: [
    {
      resolve: "gatsby-plugin-meta-redirect",
      options: {
        fromPath: "/old-url",
        toPath: "/new-url",
      },
    },
  ],
}

In this example, we are redirecting the URL "/old-url" to "/new-url". When the user visits the old URL, they will be automatically redirected to the new URL.

Conclusion

These are some ways to change the page URL in Gatsby. You can choose the option that best fits your needs and use case. Remember to test your changes thoroughly to ensure that they work as expected.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe