Search code examples
aws-amplify

How to override AWS Amplify Api domain endpoint


I have added a custom domain to the API Gateway due to CORS/Cookies/Infosec and other fun reasons.

I then added the following code to hack the correct domain into my Amplify configuration:

import { Amplify, API } from "aws-amplify"

const myfunc () => {
  const amplifyEndpoint = API._restApi._options.endpoints[0]
  Amplify.configure({
    aws_cloud_logic_custom: [
      {
        ...amplifyEndpoint,
        endpoint: process.env.REACT_APP_API_URL || amplifyEndpoint.endpoint,
      },
    ]
  })

  const response = await API.post("MyApiNameHere", "/some-endpoint", {data:"here"})
}

This works but a) is this really the correct way to do it? and b) I'm seeing a weird issue whereby the first API.post request of the day from a user is missing the authorization & x-amz-security-token headers that I expect Amplify to be magically providing. If a user refreshes the page, the headers are sent and everything works as expected.

[edit] turns out my missing headers issue is unrelated to this override, so still need to get to the bottom of that!


Solution

  • The more correct place looks to be in the index.js:

    import { Amplify, API } from "aws-amplify"
    import awsExports from "./aws-exports"
    
    Amplify.configure(awsExports)
    
    const amplifyEndpoint = API._restApi._options.endpoints[0]
    Amplify.configure({
      aws_cloud_logic_custom: [
        {
          ...amplifyEndpoint,
          endpoint: process.env.REACT_APP_API_URL || amplifyEndpoint.endpoint,
        },
      ]
    })
    

    That way it's done once - rather than needing to be done in each API call.

    Naturally you would need some more complicated logic if you were dealing with multiple endpoints.