https://github.com/postor/next-fetch
fetch for next.js
https://github.com/postor/next-fetch
Last synced: 2 months ago
JSON representation
fetch for next.js
- Host: GitHub
- URL: https://github.com/postor/next-fetch
- Owner: postor
- Created: 2017-06-21T02:43:49.000Z (almost 8 years ago)
- Default Branch: master
- Last Pushed: 2017-06-21T07:34:38.000Z (almost 8 years ago)
- Last Synced: 2025-03-16T22:18:47.102Z (2 months ago)
- Language: JavaScript
- Size: 28.3 KB
- Stars: 1
- Watchers: 2
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# next-fetch
fetch for next.js
- cookie push through for both server side and client side
- csrf push through for both server side and client side## usage
use fetch as unfetch, refer https://github.com/developit/unfetch, notice the `req` and `res` from next.js context
```
const getFetch = require('next-fetch')
const fetch = getFetch()Page.getInitialProps = ({req,res})=>{
return fetch('http://xxx/currentuser', {}, req, res)
.then(r=>r.json())
.then((user)=>{
return {about:{user, cookieDate: Cookies.get('date')}}
})
}```
getFetch function can take a config argument, by default:
```
{
csrftokenHeaderName: 'csrf-token', //header name for csrf token
csrftokenCookieName: 'csrftoken', //cookie name for csrf token
cookieHeaderName: 'custom-set-cookie' //set-cookie header can not read by js, so you have to copy set-cookie header to another key
}
```how to copy set-cookie header to custom-set-cookie
```
// in express
app.post('/auth', csrfProtection, csrfSetHeader, (req, res) => {
if(req.body && req.body.username === user.username && req.body.passwd === user.passwd){
res.cookie('user',JSON.stringify(user))//-------------------------here-----------------------------
res.header('custom-set-cookie',res.getHeader('set-cookie'))
//----------------------------------------------------------res.json(user)
}else{
res.json({error: 'wrong pass or no such account',body:req.body})
}
})```
## full code example
https://github.com/nextjs-boilerplate/nextjs-boilerplate