Node - Redirect with Parameters in Express
- Estimated read time: 3 min read
- Written by Chad Campbell on Jul 16th 2016
Recently, I wanted to move some URLs around on this site. Specifically, I had my training courses listed at a URL like this:
/about/publications/courses. Beyond that, each course was listed at something like
/about/publications/courses/[course-name]. Well, I wanted to redirect from those URLs to
In this post, I'll show you what I learned. First, I'm going to show you how to do a basic redirect in Express. Then, I'll show you how to do a redirect if you're requested URL has parameters.
Redirecting with a URL
Meeting my first requirement was pretty easy. I wanted to permanently redirect from
/courses. So, I just needed to use the
Response.redirect function. This function is baked into Express. This gave me something like this.
In this function call, I used two parameters. The first parameter I passed in was
301. This value is the HTTP status code for a permanent redirect. Well, my goal was to permanently move towards this URL structure. So, this status code made sense in my case. However, that value doesn't always make sense. I encourage you to understand what you're trying to accomplish before setting the status code. It's really important. Still, had I not included the
301, a status code of
302 (Found) would've been used.
The second parameter is the URL that I wanted to redirect to. This value can be a relative URL like I used. Or, it can be a fully qualified URL. The choice is yours. Still, I assumed that redirecting with parameters was going to be just as easy.
Redirecting with Parameters
Next, I wanted to redirect to each individual training course page. Those pages provide each course's details. At first, I assumed I could just do this:
However, that is incorrect. My brain was turned off when I tried that. But, it is the thing that made me decide to write this blog post.
This lead me to the point where I needed to build the path to my URL. So, I ended up writing the following:
This block of code appends two strings together: "/courses/" and the value of
req.params.slug. I then redirect to that URL. If I was using ES6, I could've used a template string. I chose not to do that in this blog post. The reason why is because I wanted to focus on the problem at hand and hopefully make this valuable for you.
Still, I hope you found this post helpful. If you're interested in any of my training courses, they are now located at the
/courses endpoint. If you don't believe me, you can try to use the old URL I mentioned in this post . Beyond that, thanks for reading.