Is considered a bad practice to do redirects from a Rest API server?
For example when doing OAuth2 code authorization flow.
Is considered a bad practice to do redirects from a Rest API server?
For example when doing OAuth2 code authorization flow.
Redirects are commonly used in OAuth2 to a login token back to the website. This allows the user to identify the user with an external service, and more.
/login --> discord.com/login... --> discord.com/oauth2/authorize --> /auth-redirect?code=<from_discord> --> localhost:3000/auth?token=<from_our_api>
Express.js Example:
'/auth-redirect' would be the route that the third party (e.g. Discord login) sends the code to, after the user clicks 'Authorize' on discord.com.
app.get('/auth-redirect', (req, res) => {
// ... do something with the code received from the third party
// ... return token that can be used to access our API (e.g. login)
res.redirect(`http://localhost:3000?token=${apiToken}`);
});
In this example, we are redirecting back to the website URL, and we are now able to store the token in cookies, or localStorage by getting the token from the query params.
Website Script:
// window.location.search -> '?token=...'
const query = new URLSearchParams(window.location.search);
localStorage.setItem('token', query.get('token'));
More Info on Redirects - https://moz.com/learn/seo/redirection
Redirects can be used for other things like sending success messages.
// Tell the website user, that they verified their email.
// Handle the query message on the website.
res.redirect(`${websiteURL}?message=Successfully verified your email.`)
There's also places where it does not make sense to use redirects. This assumes that the website is not built in to the API, but just sends requests to it - i.e. you are using a front-end framework.
// DELETE the user, by id, from the database.
app.delete('/user/:id', (req, res) => {
// ... delete user
// ... redirect back to the website?
res.redirect('http://localhost:3000');
});
There's a lot of use cases for redirects in APIs, especially when the website is built into the API (front-end built with back-end). Furthermore, I'd say it is good practice to use redirects in OAuth2 as routes depend on each other in a chain.
The JS code is just an example. This is how I use redirects, in an API, in one of my applications. Hopefully this helps.
Yes, it's bad, as it clashes on a definition basis with REST architecture.
While you can use it that way, it's nearly the same as using .jpg as a mean to store audio files - yes, you can do it, but you definitely shouldn't.
REST is used only for web resources and thus cannot be a part of the logic of your application. You can read more about it here.
You can, however, return the "redirection" link through the REST API. This way you won't break the convention. Or you can create a new, smaller service just for redirection.