- Newest
- Most votes
- Most comments
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:
- 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.usernameor 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; } });
- Fetch authentication session in your frontend: You can use the
fetchAuthSessionAPI 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; }
-
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.
-
Server-side context: For server-side operations in frameworks like Next.js, you can use Amplify's server-side utilities like
generateServerClientUsingCookies()orgenerateServerClientUsingReqRes()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
Relevant content
- AWS OFFICIALUpdated 5 years ago
- AWS OFFICIALUpdated 5 years 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?