Skip to content

Instantly share code, notes, and snippets.

@zprima
Created January 27, 2019 11:44
Show Gist options
  • Save zprima/9938cebbbd406ba667b4773dca950690 to your computer and use it in GitHub Desktop.
Save zprima/9938cebbbd406ba667b4773dca950690 to your computer and use it in GitHub Desktop.
medium_p1_c7
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