This is a premium alert message you can set from Layout! Get Now!

How to implement redirects in Next.js

0

Search engines and users alike do not want to find a page that does not exist or is incomplete. As a developer, you should avoid it as well because it could reduce the number of repeat visits to your site and affect how it is indexed by search engines.

Next.js is a popular framework that is built on top of the React library, and comes with a bunch of useful built-in features, one of them being handling redirects to avoid such cases.

In this article, we will set up an app and take a closer look at different ways you can implement redirects in your Next.js projects. I will also provide code snippets for both configuration files and routes and explain how they work in Next.js.

Let’s get started.

What are redirects?

Redirects enable users to transfer an executed URL to a new URL or, to put it another way, to reroute an incoming request from one path to another.

These are usually handled by the server via HTTP redire­ction status codes (3xx), which can also be understood by web crawlers.

Redirects are frequently used in situations where a section of the site does not exist or is under construction, content has been moved to a different URL, the routing system has changed, users are being redirected due to access restrictions, or many other situations.

Setting up the Next.js project

We will be using create-next-app, which is an officially supported way by Next.js to set up the development server we will use to test our redirect examples.

First, open up your terminal and run the command npx create-next-app test-app. This will create a new project folder where all the logic of the application will live.

Next, change the working directory to the newly created folder by cd test-app and then run npm run dev to start the development server.

Then, open your browser and navigate to https://localhost:3000 to view the live preview of the app.

Defined routes

The most common way to create redirects in Next.js is to use the next.config.js file, which should be located at the root level of your product structure. If it’s not, create one and include the following code:

module.exports = {
  async redirects() {
    return [
      {
        source: '/',
        destination: '/welcome',
        permanent: true,
      },
    ]
  },
}

In the snippet above, the source property is the requested route, destination is the route we want to redirect the user to, and permanent controls whether or not we want the redirect route to be cached for the client machine and search engines.

Let’s create a new route for /welcome we used in the configuration. In the root level of the pages folder, create a new file, welcome.js, and include the following code:

export default function Welcome() {
  return <h1>Welcome page</h1>;
}

Now, restart the development server by pressing Ctrl+C on your keyboard and then run; npm run dev to start it again. This is necessary for the changes we made in next.config.js to take effect. Remember to do this for further examples in the article as well.

To test the redirect, open your browser and navigate to https://localhost:3000 again. You should now be automatically redirected to https://localhost:3000/welcome.

Slug matching

Next.js supports accessing the slugs of the URL and configuring redirects for them. For this example, let’s edit next.config.js to this:

module.exports = {
  async redirects() {
    return [
      {
        source: '/draft/:slug',
        destination: '/blog/:slug',
        permanent: true,
      },
    ]
  },
}

To set up the routes, go inside the pages folder and create two new folders named draft and blog, and then create the file article.js inside both of them.

In the draft/article.js file, include the following code:

export default function Article() {
  return <h1>Source route</h1>;
}

In the blog/article.js, include the following code:

export default function Article() {
  return <h1>Destination route</h1>;
}

After restarting the dev server, try accessing https://localhost:3000/draft/article and you will be redirected to https://localhost:3000/blog/article. The slug can be any supported value in the URL unless you create a route for it and do not nest it on multiple levels.

Wildcards

To redirect nested routes you can use wildcards, which will essentially take all of the paths after the last known level and redirect to the new route. It is as simple as adding a * character to the slug you are targeting in the URL.

Switch back to next.config.js and change it to this:

module.exports = {
  async redirects() {
    return [
      {
        source: '/draft/:slug*',
        destination: '/blog/:slug*',
        permanent: true,
      },
    ]
  },
}

In order to create nested routes, we will have to make a couple of subfolders inside the draft and blog folders. Let’s just assume we want to categorize articles via technologies, so we will call both folders react. Inside both newly created folders, add the file tutorial.js.

In draft/react/tutorial.js, include the following code:

export default function Tutorial() {
  return <h1>Nested source route</h1>;
}

In blog/react/tutorial.js, include the following code:

export default function Tutorial() {
  return <h1>Nested destination route</h1>;
}

Now, restart the dev server and access https://localhost:3000/draft/react/tutorial. You should be immediately redirected to https://localhost:3000/blog/react/tutorial. Notice that the whole nested path was redirected.

Regex queries

Regex is a powerful tool that you can use to access different parts of the URL path more effectively. You will have more control over redirect behavior and will be allowed to create custom rules for redirects.

Change next.config.js to the following code:

module.exports = {
  async redirects() {
    return [
      {
        source: '/draft/:slug(^[a-z]+)',
        destination: '/blog/article',
        permanent: false,
      },
    ]
  },
}

In the code snippet above, we configured only the routes consisting just of the a to z characters being redirected to the /blog/article route, which we created earlier.

Navigate to the draft folder in your project structure and create a new file, article123.js, with the following code in it:

export default function Article123() {
  return <h1>Source route</h1>;
}

To test the regex query, restart the dev server and try to access https://localhost:3000/draft/article. You will be redirected to https://localhost:3000/blog/article, since the route consists just of letters.

Now try to access https://localhost:3000/draft/article123. You will be displayed the content of the URL you entered and not be redirected cause the route includes numbers.

Here are a couple of useful sites to help you write regex queries: regex101 and regexr.

Base path support

Next.js also supports the prefix for the base path in the URL. This might be useful if you have to set multiple redirects and do not want to repeatedly write the base path for all your routes.

Change the next.config.js to the following code:

module.exports = {
  basePath: '/content',

  async redirects() {
    return [
      {
        source: '/draft/article',
        destination: '/blog/article',
        permanent: true,
      },
      {
        source: '/draft/react/tutorial',
        destination: '/blog/react/tutorial',
        basePath: false,
        permanent: true,
      },
    ]
  },
}

In the first redirect object, the source became /content/draft/article and the destination /content/blog/article, while in the second redirect object, the base path was ignored since we set basePath to false.

Request parameters

With Next.js, you can have even further control over redirects, accessing host, header, cookie, and query values. Using the has field, you can write custom rules to control whether the redirect should be performed in different cases.

Change the next.config.js to the following code:

module.exports = {
  async redirects() {
    return [
      {
        source: '/',
        has: [
          {
            type: 'header',
            key: 'host',
            value: 'localhost:3000',
          },
        ],
        permanent: false,
        destination: '/welcome',
      },
    ];
  },
}

The type must be either header, cookie, or query. The key must be a string from the selected type to match against. The value is optional and if it is undefined, any values of the key will be matched.

In the code snippet above, we used the header and checked against the host key to have the localhost:3000 value. If these values are met in the request, the redirect will be made.

Restart the dev server and try to access https://localhost:3000. You will be redirected to https://localhost:3000/welcome, since the host value matched.

Now close the dev server with Ctrl+C and run npm run dev -- -p 8000. This will start your application on a different port. Now access your app on https://localhost:8000. This time you will not be redirected, since the host value did not match your redirect configuration.

API redirects

Next.js comes with a built-in way of handling the API calls. You can use the redirect method to perform a redirect if a certain response is successful. This can be really handy when logging in users, submitting forms, and other use cases.

To create a new API route, navigate to the api folder inside pages and create a new file, data.js, with the following code:

export default async function handler(req, res) {
  console.log(`Name: ${req.body.name}`);
  try {
    // some await stuff here
    res.redirect(307, '/welcome');
  } catch (err) {
    res.status(500).send({ error: 'Error while fetching data' });
  }
}

Then, navigate to the root level of the pages folder and create a new file, form.js, to create the form itself. Include the following code in the newly created file:

export default function Form() {
  return (
    <form action='/api/data' method='post'>
      <label htmlFor='name'>Your name:</label>
      <input type='text' id='name' name='name' />
      <button type='submit'>Submit</button>
    </form>
  );
}

Now open your browser and navigate to https://localhost:3000/form. You will be presented with the input field to enter your name and submit button to send the value to the API. Enter any value, submit it and you should be redirected to https://localhost:3000/welcome.

To make sure the API received the value you entered, switch back to the terminal and check the printed logs. The value should be displayed there.

getStaticProps and getServerSideProps

If you want to set redirects via the built-in pre-render methods of Next.js, you can include them in getStaticProps or getServerSideProps.

Using getStaticProps, the page will be pre-rendered at build time (static site generation).

To set up an example, navigate to the root level of the pages folder and edit index.js:

export default function Home() {
  return <h1>Home page</h1>;
}

export async function getStaticProps() {
  const content = null;

  if (!content) {
    return {
      redirect: {
        permanent: false,
        destination: '/welcome',
      },
    };
  }

  return {
    props: {},
  };
}

Similarly, for server-side rendering (SSG), you would use getServerSideProps, which will make sure Next.js pre-renders the page on each request.

To set up the SSG example, edit index.js as shown below:

export default function Home() {
  return <h1>Home page</h1>;
}

export async function getServerSideProps() {
  const content = null;

  if (!content) {
    return {
      redirect: {
        permanent: false,
        destination: '/welcome',
      },
    };
  }

  return {
    props: {},
  };
}

To test either of the two cases, try accessing https://localhost:3000, and you will be automatically redirected to https://localhost:3000/welcome since the redirect rules in getStaticProps or getServerSideProps were executed.

Conclusion

In this article, we looked at a number of ways how you can implement redirects in Next.js. First, we used next.config.js and wrote custom configurations for predefined routes, accessed single-level and nested routes, and used regex to increase the control of redirects.

Then, we also took a closer look at how you can create redirects based on the received request params. Lastly, we looked at how to implement redirects using the API routes and static site generation versus server-side rendering.

I hope with this article you learned something new, and from this point onward you will be able to create redirects for all of your use cases in your future Next.js apps.

The post How to implement redirects in Next.js appeared first on LogRocket Blog.



from LogRocket Blog https://ift.tt/9PMjznW
Gain $200 in a week
via Read more

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment

Search This Blog

To Top