amplify-auth-next-storage
Isomorphic cookie storage for Next.js apps using @aws-amplify/auth
Installation
$ npm install amplify-auth-next-storage
Options
new NextStorage(ctx, options)
ctx
is the Next.js ctx object, only required server-side. Pass null
or undefined
on the client-side.options
are identical to Amplify's cookieStorage
configuration options.
https://aws-amplify.github.io/docs/js/authentication#manual-setup
Option | Type | Default | Description |
---|
domain (required) | string | none | Cookies domain |
expires | number | 365 | Cookie expiration in days |
path | string | / | Cookies path |
secure | boolean | true | Cookie secure flag |
Usage
import Auth from '@aws-amplify/auth';
import NextStorage from 'amplify-auth-next-storage';
export function configurePool(ctx) {
Auth.configure({
region: 'us-east-1',
userPoolId: 'us-east-1_xxxxx',
userPoolWebClientId: 'xxxxxxxxxxxxxxx',
storage: new NextStorage(ctx, {
domain: '.yourdomain.com',
expires: 365,
path: '/',
secure: true,
}),
});
}
import React from 'react';
import { configurePool } from 'utils/auth-utils';
import fetch from 'node-fetch';
global.fetch = fetch;
const YourApp = ({ Component, pageProps }) => {
configurePool();
return <Component {...pageProps} />;
};
YourApp.getInitialProps = async (appContext) => {
const appProps = await App.getInitialProps(appContext);
configurePool(appContext.ctx);
return { ...appProps };
};
export default YourApp;
import React from 'react';
import { configurePool } from 'utils/auth-utils';
const FancyComponent = () => {
Auth.currentUserInfo().then(currentUser => console.log(currentUser));
return <div>Fancy Component</div>;
}
FancyComponent.getInitialProps = async (ctx) => {
configurePool(ctx);
await Auth.currentUserInfo().then(currentUser => console.log(currentUser));
return {};
}
Notes
If you're struggling to get Auth.configure
to work properly on the server side, one workaround is to use something like node-fetch
as the global fetch.
import fetch from 'node-fetch';
global.fetch = fetch;