mirror of
https://github.com/terribleplan/next.js.git
synced 2024-01-19 02:48:18 +00:00
798ae043ac
Fixes #153 This is my attempt at https://github.com/zeit/next.js/issues/153 Following @rauchg instructions: - it uses an authentication helper across pages which returns a token if there's one - it has session synchronization across tabs - <strike>I deployed a passwordless backend on `now.sh` (https://with-cookie-api.now.sh, [src](https://github.com/j0lv3r4/next.js-with-cookies-api))</strike> The backend is included in the repository and you can deploy everything together by running `now` Also, from reviewing other PRs, I made sure to: - use [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch). - use [next-cookies](https://www.npmjs.com/package/next-cookies). Here's a little demo: ![GIF](https://i.imgur.com/067Ph56.gif)
30 lines
843 B
JavaScript
30 lines
843 B
JavaScript
const { send, createError, run } = require('micro')
|
|
const fetch = require('isomorphic-unfetch')
|
|
|
|
const profile = async (req, res) => {
|
|
if (!('authorization' in req.headers)) {
|
|
throw createError(401, 'Authorization header missing')
|
|
}
|
|
|
|
const auth = await req.headers.authorization
|
|
const { token } = JSON.parse(auth)
|
|
const url = `https://api.github.com/user/${token}`
|
|
|
|
try {
|
|
const response = await fetch(url)
|
|
|
|
if (response.ok) {
|
|
const js = await response.json()
|
|
// Need camelcase in the frontend
|
|
const data = Object.assign({}, { avatarUrl: js.avatar_url }, js)
|
|
send(res, 200, { data })
|
|
} else {
|
|
send(res, response.status, response.statusText)
|
|
}
|
|
} catch (error) {
|
|
throw createError(error.statusCode, error.statusText)
|
|
}
|
|
}
|
|
|
|
module.exports = (req, res) => run(req, res, profile)
|