DEV Community

Cover image for Adding Authentication to a Nuxt App with AWS Amplify
Nader Dabit for AWS

Posted on

Adding Authentication to a Nuxt App with AWS Amplify

The code for this app is located here

AWS Amplify offers a comprehensive set of tools and services that enable mobile and front-end web developers to quickly and easily build secure, scalable full stack applications, powered by AWS services.

In this post you'll learn how to add authentication to a Nuxt app using AWS Amplify.

Getting started

To get started, install and configure the Amplify CLI if you have not already done so:

npm install -g @aws-amplify/cli

amplify configure
Enter fullscreen mode Exit fullscreen mode

For help on configuring the Amplify CLI, check out the docs here or the video walkthrough here.

Next, create a new Nuxt app and change into the directory:

npx create-nuxt-app nuxt-auth-app

cd nuxt-auth-app
Enter fullscreen mode Exit fullscreen mode

Install the Amplify JS and Amplify Vue UI libraries:

npm install aws-amplify @aws-amplify/cli
Enter fullscreen mode Exit fullscreen mode

From inside the directory of the new project, initialize a new Amplify project:

amplify init

? Enter a name for the project: nuxtauth
? Enter a name for the environment: dev
? Choose your default editor: <your-default-text-editor>
? Choose the type of app that you're building: javascript
? What javascript framework are you using: vue
? Source Directory Path: .
? Distribution Directory Path: dist
? Build Command:  npm run-script generate
? Start Command: npm run-script start
Enter fullscreen mode Exit fullscreen mode

Next, add authentication using the add command:

amplify add auth

? Do you want to use the default authentication and security configuration? Default configuration
? How do you want users to be able to sign in? Username
? Do you want to configure advanced settings? No, I am done.
Enter fullscreen mode Exit fullscreen mode

Configuring Amplify with Nuxt

Next, we need to configure the Amplify project we just created to be recognized by the Nuxt app. To do so, create a new file in the plugins directory called amplify.js and add the following code:

// plugins/amplify.js
import Amplify from 'aws-amplify'
import '@aws-amplify/ui-vue';
import config from '../src/aws-exports'
Amplify.configure(config)
Enter fullscreen mode Exit fullscreen mode

Adding authentication

Now that the authentication service has been created and Amplify has been configured, we can add the code to create the authentication flow.

Create a file called profile.js and add the following code:

<template>
  <div>
    <amplify-authenticator v-if="authState !== 'signedin'" class="container" />
    <div v-if="authState === 'signedin' && user">
      <h1>Hello, {{user.username}}</h1>
      <button v-on:click="signOut">Sign Out</button>
    </div>
  </div>
</template>

<script>
import { onAuthUIStateChange } from '@aws-amplify/ui-components'
import { Auth }  from 'aws-amplify';

export default {
  created() {
    onAuthUIStateChange((authState, authData) => {
      this.authState = authState;
      this.user = authData;
    })
  },
  data() {
    return { user: undefined, authState: undefined }
  },
  methods: {
    signOut: async () => Auth.signOut()
  },
  beforeDestroy() {
    return onAuthUIStateChange;
  }
}
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
}

:root {
  --amplify-primary-color: #4287f5;
  --amplify-primary-tint: #005cf0;
  --amplify-primary-shade: #005cf0;
}
</style>
Enter fullscreen mode Exit fullscreen mode

Next, open layouts/default.vue and update the template to add links that enable navigation between the main page and the new profile page:

<template>
  <div>
    <nuxt-link to="/">Home</nuxt-link>
    <nuxt-link to="/profile">Profile</nuxt-link>
    <Nuxt />
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode

To test it out, run the dev command:

npm run dev
Enter fullscreen mode Exit fullscreen mode

When the app runs, you should be able to navigate to /profile and sign up.

🎉 Congrats, you've successfully added authentication to your Next app!

Deploying to AWS

If you'd like to deploy the app to AWS, you can do so using the CLI:

amplify add hosting

? Select the plugin module to execute: Hosting with Amplify Console
? Choose a type: Manual deployment
Enter fullscreen mode Exit fullscreen mode

You can then deploy the site and subsequent updates using the publish command:

amplify publish
Enter fullscreen mode Exit fullscreen mode

Creating a custom Authentication flow

In this guide you've learned how to add authentication using the AWS Amplify UI library for Vue. In many cases though you may need to build a custom authentication configuration to have complete control over your authentication flow.

To create a custom authentication flow, you can use the Auth class directly for complete control over user management.

To learn more, check out the the documentation for Amplify authentication or the main Amplify docs.

Social Sign In

Amplify also supports OAuth support for social sign in.

To update your project to implement social sign in, run the update command:

amplify update auth

> Choose "Apply default configuration with Social Provider"
Enter fullscreen mode Exit fullscreen mode

Once configured, you can then sign in users in using the Auth class:

Auth.federatedSignIn({provider: 'Google'})
Enter fullscreen mode Exit fullscreen mode

To learn more about how to set this up, check out the documentation.


Cover image by Matt Gross

Top comments (6)

Collapse
 
aossey profile image
Michael Aossey

Hi @dabit3 ,
Thank you for the contribution, there is not a lot of info out there on nuxt and Amplify.

I wanted to point out a few things to help improve this for others:

As @arunans23 pointed out - npm install should be

npm install aws-amplify @aws-amplify/ui-vue
Enter fullscreen mode Exit fullscreen mode

In profile\amplify.js file, the aws-exports.js file should import with path ~/aws-exports since there is no src directory in nuxt

The plugin also needs to be added to nuxt-config.js in the plugins array as client-only by adding

{ src: '~/plugins/amplify.js', mode: 'client' }
Enter fullscreen mode Exit fullscreen mode

The profile file should be in the pages directory and call profile.vue rather than profile.js

Collapse
 
saunved profile image
Saunved

Hi, do you have any resources that could help me setup Amplify with an existing auth configuration? I created an amplify plugin file (docs.amplify.aws/lib/auth/start/q/...) and added it to nuxt.config.js, but I get this error:

AuthError - 
Error: Amplify has not been configured correctly. 
The configuration object is missing required auth properties.
Enter fullscreen mode Exit fullscreen mode

Just wondering in case you have any experience with this.

Collapse
 
seravault profile image
Seravault

This is excellent information especially in the comments. I'm using Vue3 and here's what I've found thus far:

yarn add aws-amplify @aws-amplify/ui-components

Set your "src" directory for Amplify to "plugins". Add your amplify.js file with the following contents:

import Amplify from 'aws-amplify';
import {
applyPolyfills,
defineCustomElements,
} from '@aws-amplify/ui-components/loader';
import awsconfig from './aws-exports';

applyPolyfills().then(() => {
defineCustomElements(window);
});

Amplify.configure(awsconfig);

I'm getting an ESLinter error because apparently Vue3 does away with default exports. I'll figure it out, but in the meantime, it works.

aws.amazon.com/blogs/mobile/amplif...

Collapse
 
arunans23 profile image
Arunan Sugunakumar

Great post. I think instead of @aws-amplify/ui-vue you accidently mentioned the cli to install in npm install aws-amplify @aws-amplify/cli

Collapse
 
jmarshall9120 profile image
jmarshall9120 • Edited

Warning, this implementation does NOT WORK. You must include the plugin declaration in the nuxt.config.js. See Michael Assoys post for more details.

Collapse
 
seravault profile image
Seravault

Found the key to Vue 3. You need to import your Amplify with brackets :
import { Amplify } from 'aws-amplify';
import awsconfig from './aws-exports';

Amplify.configure(awsconfig);