Skip to content

Instantly share code, notes, and snippets.

@Lightnet
Last active July 18, 2022 17:10
Show Gist options
  • Save Lightnet/6555e9b48db845d1149374f48a8bbcb1 to your computer and use it in GitHub Desktop.
Save Lightnet/6555e9b48db845d1149374f48a8bbcb1 to your computer and use it in GitHub Desktop.
bun js http server cookie simple
{
"name": "bunpreact",
"version": "1.0.0",
"description": "",
"main": "http.js",
"scripts": {
"dev": "bun run server.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"cookie": "^0.5.0",
"preact-compat": "^3.19.0"
}
}
import cookie from "cookie";
Bun.serve({
//http server port
port: 3000,
// http handler request
fetch(req) {
console.log("URL",req.url)
//get browser client
for(const key of req.headers.keys()){
console.log(key)
}
//get browser cookie
console.log(req.headers.get('cookie'))
//string cookie from header only string value
const sCookie = req.headers.get('cookie')
if(sCookie){
console.log("Cookie Found!")
//string to object json
const dCookie = cookie.parse(sCookie)
console.log(dCookie)
}else{
console.log("Cookie Not Found!")
}
// set up header to return to browser client
const headers = new Headers();
headers.set('Set-Cookie', cookie.serialize('test','testx'))
return new Response("Bun, Hello world!", {
headers: headers, //must match param name
status: 200 // good = 200, bad = 500 (error page request)
});
},
error(error) {
return new Response("Uh oh!!\n" + error.toString(), { status: 500 });
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment