Introduction#

Github shows

  • Amplify NextJS withAuthenticator
  • NextJS Client Side Auth
  • NextJS Server Side Auth
  • References 1, 2, and 3
  • Video Demo
netjs auth client server

Client Side#

using SignUp, SignIn, or withAuthenticator is client side

import Head from 'next/head'
import Image from 'next/image'
import { Inter } from '@next/font/google'
import styles from '../styles/Home.module.css'
import { withAuthenticator } from '@aws-amplify/ui-react'
const inter = Inter({ subsets: ['latin'] })
const Home = ({ signOut, user }: { signOut: any; user: any }) => {
return (
<>
<main className={styles.main}>
<div className={styles.description}>
<p>
Welcome {user.username}&nbsp;
<code className={styles.code}>pages/index.tsx</code>
</p>
</div>
<button
style={{ background: 'orange', width: '200px' }}
onClick={signOut}
>
Sign Out
</button>
</main>
</>
)
}
export default withAuthenticator(Home)

Server Side#

the key is to use withSSRContext here

  • ssr: true in aws-exports.js
  • amplify persists credentials on the client in cookies so that subsequent requests to the server have access to them
  • withSSRContext utility creates an instance of Amplify scoped to a single request (req) using those cookie credentials.
import { withSSRContext } from 'aws-amplify'
export async function getServerSideProps({ req }: { req: any }) {
const SSR = withSSRContext({ req })
try {
const user = await SSR.Auth.currentAuthenticatedUser()
return {
props: {
user: JSON.stringify(user)
}
}
} catch (error) {
console.log(error)
const user = null
return {
props: {
user: user
}
}
}
}
const Profile = ({ user }: { user: any }) => {
if (!user) {
return (
<div
style={{
display: 'flex',
margin: 'auto',
maxWidth: '80vw',
justifyContent: 'center'
}}
>
<p>
Not Authenticated,{' '}
<a href="/" style={{ color: 'blue', textDecoration: 'underline' }}>
Please Log In First
</a>
</p>
</div>
)
}
return (
<div
style={{
display: 'flex',
margin: 'auto',
maxWidth: '80vw',
justifyContent: 'center'
}}
>
{user && <p>Welcome {JSON.parse(user).username}</p>}
</div>
)
}
export default Profile