1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00
next.js/examples/with-cookie-auth/www/pages/profile.js
Juan Olvera 798ae043ac Example with cookie auth (#5821)
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)
2018-12-14 23:05:54 +01:00

74 lines
1.6 KiB
JavaScript

import Router from 'next/router'
import fetch from 'isomorphic-unfetch'
import Layout from '../components/layout'
import auth, { withAuthSync } from '../utils/auth'
const Profile = withAuthSync(props => {
const { name, login, bio, avatarUrl } = props.data
return (
<Layout>
<img src={avatarUrl} alt='Avatar' />
<h1>{name}</h1>
<p className='lead'>{login}</p>
<p>{bio}</p>
<style jsx>{`
img {
max-width: 200px;
border-radius: 0.5rem;
}
h1 {
margin-bottom: 0;
}
.lead {
margin-top: 0;
font-size: 1.5rem;
font-weight: 300;
color: #666;
}
p {
color: #6a737d;
}
`}</style>
</Layout>
)
})
Profile.getInitialProps = async ctx => {
const token = auth(ctx)
const apiUrl = process.browser
? `https://${window.location.host}/api/profile.js`
: `https://${ctx.req.headers.host}/api/profile.js`
const redirectOnError = () =>
process.browser
? Router.push('/login')
: ctx.res.writeHead(301, { Location: '/login' })
try {
const response = await fetch(apiUrl, {
credentials: 'include',
headers: {
'Content-Type': 'application/json',
Authorization: JSON.stringify({ token })
}
})
if (response.ok) {
return await response.json()
} else {
// https://github.com/developit/unfetch#caveats
return redirectOnError()
}
} catch (error) {
// Implementation or Network error
return redirectOnError()
}
}
export default Profile