i want to register and login customer via storefront api for my shopify mobile using reactnative, any advise or working example please
In your app, you’d use the customerCreate mutation to register new customers, it could look something like this:
import client from './ShopifyApi';
const CUSTOMER_CREATE_MUTATION = `
mutation customerCreate($input: CustomerCreateInput!) {
customerCreate(input: $input) {
customer {
id
email
firstName
lastName
}
customerUserErrors {
code
field
message
}
}
}`;
export const registerCustomer = async (customerData) => {
try {
const variables = { input: customerData };
const response = await client.request(CUSTOMER_CREATE_MUTATION, variables);
if (response.customerCreate.customerUserErrors.length > 0) {
console.log(response.customerCreate.customerUserErrors);
throw new Error(response.customerCreate.customerUserErrors[0].message);
}
return response.customerCreate.customer;
} catch (error) {
console.error("Registration error:", error);
throw error;
}
};
And you’d use the customerAccessTokenCreate mutation to authenticate a customer and retrieve a token, it would look something like this:
const CUSTOMER_LOGIN_MUTATION = `
mutation customerAccessTokenCreate($input: CustomerAccessTokenCreateInput!) {
customerAccessTokenCreate(input: $input) {
customerAccessToken {
accessToken
expiresAt
}
customerUserErrors {
code
field
message
}
}
}`;
export const loginCustomer = async (email, password) => {
try {
const variables = {
input: { email, password }
};
const response = await client.request(CUSTOMER_LOGIN_MUTATION, variables);
if (response.customerAccessTokenCreate.customerUserErrors.length > 0) {
throw new Error(response.customerAccessTokenCreate.customerUserErrors[0].message);
}
return response.customerAccessTokenCreate.customerAccessToken;
} catch (error) {
console.error("Login error:", error);
throw error;
}
};
Hi Liam , thanks for the reply .
the registration works perfect as you suggested but when i try to login it gives me error for the "Unidentified user " .
export const CUSTOMER_LOGIN_MUTATION = `
mutation customerAccessTokenCreate($input: CustomerAccessTokenCreateInput!) {
customerAccessTokenCreate(input: $input) {
customerAccessToken {
accessToken
expiresAt
}
userErrors {
field
message
}
}
}
`;
export const loginApi = async ({email, password}) => {
try {
const response = await shopifyApi.post('', {
query: CUSTOMER_LOGIN_MUTATION,
variables: {
input: {
email,
password,
},
},
});
const {data, errors} = response.data;
if (errors?.length) throw new Error(errors[0]?.message);
if (data.customerAccessTokenCreate?.userErrors?.length)
throw new Error(data.customerAccessTokenCreate.userErrors[0].message);
return data.customerAccessTokenCreate;
} catch (error) {
throw new Error(error.message || 'Login failed');
}
};