Created
January 27, 2019 11:44
-
-
Save zprima/9938cebbbd406ba667b4773dca950690 to your computer and use it in GitHub Desktop.
medium_p1_c7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from 'axios'; | |
import Router from 'next/router'; | |
import { Cookies } from 'react-cookie'; | |
// set up cookies | |
const cookies = new Cookies(); | |
const serverUrl = 'http://localhost:3001'; | |
export async function handleAuthSSR(ctx) { | |
let token = null; | |
// if context has request info aka Server Side | |
if (ctx.req) { | |
// ugly way to get cookie value from a string of values | |
// good enough for demostration | |
token = ctx.req.headers.cookie.replace(/(?:(?:^|.*;\s*)token\s*\=\s*([^;]*).*$)|^.*$/, "$1"); | |
} | |
else { | |
// we dont have request info aka Client Side | |
token = cookies.get('token') | |
} | |
try { | |
const response = await axios.get(serverUrl + "/api/token/ping", { headers: { 'Authorization': token } }); | |
// dont really care about response, as long as it not an error | |
console.log("token ping:", response.data.msg) | |
} catch (err) { | |
// in case of error | |
console.log(err.response.data.msg); | |
console.log("redirecting back to main page"); | |
// redirect to login | |
if (ctx.res) { | |
ctx.res.writeHead(302, { | |
Location: '/' | |
}) | |
ctx.res.end() | |
} else { | |
Router.push('/') | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment