Skip to content

Making Logged-In User ID Globally accessible in Amplify Queries and Mutations

0

I am working on a React Native app using AWS Amplify. For most of my custom queries and mutations, I need the logged-in user’s ID, and currently, I’m passing it manually each time.

I have created custom SQL queries and Lambda functions because I sometimes need to fetch joined table data or update multiple tables in a single API call.

Is there a recommended way to make the logged-in user ID globally accessible so it can be used automatically in any query or mutation?

Thanks in advance for your guidance!

1 Answer
0

In AWS Amplify, you can access the logged-in user's ID automatically in your custom queries and mutations without having to pass it manually each time. Here are some approaches you can use:

  1. Use the context object in your backend handlers: When you define custom queries or mutations in Amplify Gen 2, the handler function receives a context object that contains the identity of the authenticated user. You can access the user ID with ctx.identity.username or other relevant attributes.

For example:

data.query('getFilteredData', {
returnType: ['YourDataType'],
handler: async (ctx) => {
const userId = ctx.identity.username;
// Use userId in your query logic
// ...
return result;
}
});
  1. Fetch authentication session in your frontend: You can use the fetchAuthSession API from Amplify to retrieve the current user's session information:
import { fetchAuthSession } from 'aws-amplify/auth';

async function getUserInfo() {
const session = await fetchAuthSession();
const userId = session.tokens?.idToken?.payload.sub; // or other relevant user identifier
return userId;
}
  1. For Lambda functions: If you're using Lambda functions for custom operations, you can extract the user ID from the event object that contains the JWT token. The user information is passed in the request context when the user is authenticated.

  2. Server-side context: For server-side operations in frameworks like Next.js, you can use Amplify's server-side utilities like generateServerClientUsingCookies() or generateServerClientUsingReqRes() to maintain authentication context.

By implementing one of these approaches, you can avoid manually passing the user ID in each query or mutation, making your code cleaner and more maintainable.
Sources
Backend operations and data filtering on call | AWS re:Post
User becomes undefined after refresh, preventing data fetching | AWS re:Post
Authenticate existing React application users by using Amazon Cognito and AWS Amplify UI - AWS Prescriptive Guidance

answered a year ago

  • const sqlSchema = generatedSqlSchema.authorization(allow => allow.guest()) .addToSchema({ createNewLocationWithLongLat: a.mutation() .arguments({ lat: a.float().required(), long: a.float().required(), name: a.string().required(), address: a.string().required() }) .returns(a.json().array()) .authorization(allow => allow.authenticated()) .handler(a.handler.sqlReference('./createNewLocationWithLongLat.sql')) })

    INSERT INTO locations (name, address, geom) VALUES (:name, :address, ST_GEOMFROMTEXT(CONCAT('POINT (', :long, ' ', :lat, ')'), 4326));

    how to get the LoggedInUserID in such queries/mutations which reference to the SQL file?

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.