Skip to content

Instantly share code, notes, and snippets.

@mtliendo
Last active December 1, 2021 21:47
Show Gist options
  • Save mtliendo/8686f7e57b70d3d8c6a33c211573e160 to your computer and use it in GitHub Desktop.
Save mtliendo/8686f7e57b70d3d8c6a33c211573e160 to your computer and use it in GitHub Desktop.
Using Amplify command hooks, showcase how to upload the aws-exports file to Vercel after the `amplify push` command is ran. This allows customers to use the Amplify CLI, and JavaScript modules while hosting their app on Vercel.
/**
* @param data { { amplify: { environment: string, command: string, subCommand: string, argv: string[] } } }
* @param error { { message: string, stack: string } }
*/
import { execSync } from 'child_process'
import { writeFileSync, readFileSync, copyFileSync, rmSync } from 'fs'
const hookHandler = async (data, error) => {
const VERCEL_ENVVAR_NAME = 'NEXT_PUBLIC_AMPLIFY_CONFIG'
console.log('creating .mjs file from aws-exports...\n')
copyFileSync('./aws-exports.js', './aws-exports.mjs')
const config = await import('../../aws-exports.mjs')
console.log('config successfully imported \n')
console.log('creating temporary text file to store secrets \n')
writeFileSync('./exportConfig.txt', JSON.stringify(config))
console.log('text file successfully created \n')
console.log('uploading the secrets to Vercel...\n')
try {
execSync(
`vercel env add ${VERCEL_ENVVAR_NAME} production < ./exportConfig.txt`
)
} catch (e) {
console.log(
'error uploading to vercel, trying to remove and upload again...'
)
try {
console.log('attempting...\n')
execSync(`vercel env rm ${VERCEL_ENVVAR_NAME} production -y`)
execSync(
`vercel env add ${VERCEL_ENVVAR_NAME} production < ./exportConfig.txt`
)
} catch (e) {
console.log('still not working\n', e.toString())
rmSync('./aws-exports.mjs')
rmSync('./exportConfig.txt')
throw Error('exiting')
}
}
console.log(
'Successfully uploaded environment variable to Vercel. Cleaning up files...\n'
)
rmSync('./aws-exports.mjs')
rmSync('./exportConfig.txt')
console.log(
` Use this in the Amplify.configure() method by passing in process.env.${VERCEL_ENVVAR_NAME}. \n`
)
}
const getParameters = async () => {
return JSON.parse(readFileSync(0, { encoding: 'utf8' }))
}
getParameters()
.then((event) => hookHandler(event.data, event.error))
.catch((err) => {
console.error(err)
process.exitCode = 1
})
@mtliendo
Copy link
Author

mtliendo commented Dec 1, 2021

This makes the following assumptions:

  1. The post-push.js file is in a hooks directory that has a package.json
  2. The package.json file has a type:module key pair.
  3. The local environment has the Vercel CLI installed
  4. The local project has been linked to Vercel using vercel link
  5. The project already exists as a repo on GitHub and has an initial deploy to Vercel (this step is presumably done being adding in Amplify)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment