Express res.links() Method
What you’ll learn
- How to build HTTP
Linkheaders withres.links(). - How to expose pagination links (
next,prev,first,last). - How to combine link headers with JSON API responses.
- How to avoid malformed link header output.
Syntax
javascript
res.links({
next: 'https://api.example.com/items?page=2',
last: 'https://api.example.com/items?page=10'
})1
Add pagination links in API response
javascript
app.get('/api/products', function (req, res) {
res.links({
next: 'https://api.example.com/products?page=2',
last: 'https://api.example.com/products?page=20'
});
res.json({ page: 1, items: [] });
});2
Provide first, prev, and next relations
javascript
app.get('/api/orders', function (req, res) {
res.links({
first: 'https://api.example.com/orders?page=1',
prev: 'https://api.example.com/orders?page=4',
next: 'https://api.example.com/orders?page=6'
});
res.json({ page: 5, items: [] });
});3
Append relation links before metadata response
javascript
app.get('/api/articles', function (req, res) {
res.links({ next: '/api/articles?page=2' });
res.status(200).json({ total: 120, page: 1 });
});⚠️ Common pitfalls
- Ensure relation URLs are valid and correctly encoded.
- Keep relation names meaningful (
next,prev,first,last). - Set links before ending the response so headers are included.
❓ FAQ
It sets or appends formatted HTTP Link header values from a relation-to-URL object.
They communicate related resources like next, prev, first, and last for pagination and API discoverability.
Yes, set links and then send JSON so clients can use both body and headers.
It appends correctly formatted link segments, depending on existing header state.
Absolute URLs are often clearer for API clients, though relative URLs may work depending on consumers.
Did you know?
res.links() helps build RFC-style Link headers such as rel="next" and rel="prev".
4 people found this page helpful
