Let's imagine a REST API that can return JSON, XML, HTML and other formats. In case of a browser web client without JavaScript enabled, the API return HTML. Tokens are used for authentication and authorization.
In a classic website project, it can happen that a redirection need to be made from a page A to another page B. It can be used for example to display a welcome message or an error message in another page. In this case, to display a message (flash for example) from page A on the page B, we would normally use session. Two simple (and minify) examples in express (but the concept is the same in other technologies):
// With session directly
const session = require('express-session');
app.use(session({ /* ... */ });
function (req, res, next) {
req.session.message = 'Welcome, you are connected';
return res.redirect('/');
}
<p class="message">${ session.message }</p>
// With a library as connect-flash
const flash = require('connect-flash');
app.use(flash());
function (req, res, next) {
req.flash('error', {
message: 'An error!',
});
return res.redirect('/login');
}
<p class="message">${ flash.message }</p>
Now, based on REST principles, to respect the stateless constraints, it should not use sessions which store a state between two requests.
My question is : How a stateless web server should normally pass messages between two requests ? (in case of a redirection)
- Session : Not stateless as required
- DB ?
- Query string ?
- Cookie ?
- Other ?
Note : I know how implement these solutions but i am asking for a right way to do that in the case of a stateless web server. How normally REST API implement it ?
Following this question, I have two (optionnal) misunderstandings.
Based on this stack overflow answer :
That does not preclude other services that the web server talks to from maintaining state about business objects such as shopping carts, just not about the client's current application/session state.
What does other services means here ?
Based on this comment from the same answer :
The authentication can be implicit in the state, do you think that facebook does a "database access" on every request of its REST API? Or Google for that matter? hint: no
What does it means by implicit in the state ? If it is that they use token or a similar authentication process, then they should make a database access each time to get a fresh user, no ?
Thank you in advance.
Other Service
could be Redis or any NoSQL database that could store a user state between API calls. Seebacked service
definition from 12 Factor App.