Created
September 2, 2020 12:19
-
-
Save kandros/b03b240e3ebc3ac7f4419f8a2781d24a to your computer and use it in GitHub Desktop.
NextJS cognito cookie redirect to login
This file contains 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 { UserProvider } from "@app/context/user-context" | |
import "@app/styles/font.css" | |
import "@app/styles/global.css" | |
import "@app/styles/reset.css" | |
import { NextComponentType } from "next" | |
import App, { AppContext, AppInitialProps, AppProps } from "next/app" | |
import Head from "next/head" | |
import { parseCookies } from "nookies" | |
const CustomApp: NextComponentType<AppContext, AppInitialProps, AppProps> = ({ Component, pageProps }) => { | |
return ( | |
<> | |
<Head> | |
<title>next-starter</title> | |
</Head> | |
<div> | |
<UserProvider> | |
<Component {...pageProps} /> | |
</UserProvider> | |
</div> | |
</> | |
) | |
} | |
const lastUserCookieKey = `CognitoIdentityServiceProvider.${process.env.NEXT_PUBLIC_AWS_COGNITO_CLIENT_ID}.LastAuthUser` | |
const getTokenIdCookieKey = (userId: string) => | |
`CognitoIdentityServiceProvider.${process.env.NEXT_PUBLIC_AWS_COGNITO_CLIENT_ID}.${userId}.idToken` | |
CustomApp.getInitialProps = async (appContext) => { | |
const appProps = await App.getInitialProps(appContext) | |
/* | |
validate della signature del token | |
*/ | |
const cookiesMap = parseCookies(appContext.ctx) | |
const userId = cookiesMap[lastUserCookieKey] | |
const tokenId = cookiesMap[getTokenIdCookieKey(userId)] | |
if (appContext.router.pathname !== "/login" && !tokenId /* user not found */) { | |
appContext.ctx.res | |
?.writeHead(302, { | |
Location: "/login", | |
}) | |
.end() | |
} | |
return { ...appProps } | |
} | |
export default CustomApp |
This file contains 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
const cookieStorageConfig = { | |
domain: "localhost", | |
secure: false, | |
path: "/", | |
expires: 365, | |
} | |
export const userPool = new CognitoUserPool({ | |
UserPoolId: process.env.NEXT_PUBLIC_AWS_COGNITO_USER_POOL_ID as string, | |
ClientId: process.env.NEXT_PUBLIC_AWS_COGNITO_CLIENT_ID as string, | |
Storage: new CookieStorage(cookieStorageConfig), | |
}) | |
const cognitoUser = new CognitoUser({ | |
Username: email, | |
Pool: userPool, | |
Storage: new CookieStorage(cookieStorageConfig), | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment