How to use Metadata with Lock Library

This article describes how you can define and update the user's user_metadata, using Auth0's Lock library. If you are not familiar with user_metadata, refer to User Metadata. If you need more details on how to install, initialize and use Lock, refer to Lock for Web.

Define User Metadata on Signup

For information on adding user_metadata on signup, see the section on Lock Additional Signup Fields

Read User Metadata

You can read the user's user_metadata properties the same way you would for any user profile property. This example retrieves the value associated with user_metadata.hobby:

lock.getUserInfo(accessToken, function(error, profile) {
  if (!error) {
    document.getElementById('hobby').textContent = profile.user_metadata.hobby;
  }
});

NOTE: For details on how to initialize lock refer to new Auth0Lock(clientID, domain, options)

Update User Metadata

You can update the metadata properties with calls to the Auth0 Management API. To do so, make a PATCH call to the Update a user endpoint.

Here is a sample request, that adds the user's home address as a second-level property:


curl --request PATCH \
  --url https://youraccount.auth0.com/api/v2/users/user_id \
  --header 'authorization: Bearer YOUR_TOKEN' \
  --header 'content-type: application/json' \
  --data '{"user_metadata": {"addresses": {"home": "123 Main Street, Anytown, ST 12345"}}}'
var client = new RestClient("https://youraccount.auth0.com/api/v2/users/user_id");
var request = new RestRequest(Method.PATCH);
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", "Bearer YOUR_TOKEN");
request.AddParameter("application/json", "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io/ioutil"
)

func main() {

	url := "https://youraccount.auth0.com/api/v2/users/user_id"

	payload := strings.NewReader("{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}")

	req, _ := http.NewRequest("PATCH", url, payload)

	req.Header.Add("authorization", "Bearer YOUR_TOKEN")
	req.Header.Add("content-type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
HttpResponse<String> response = Unirest.patch("https://youraccount.auth0.com/api/v2/users/user_id")
  .header("authorization", "Bearer YOUR_TOKEN")
  .header("content-type", "application/json")
  .body("{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}")
  .asString();
var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://youraccount.auth0.com/api/v2/users/user_id",
  "method": "PATCH",
  "headers": {
    "authorization": "Bearer YOUR_TOKEN",
    "content-type": "application/json"
  },
  "processData": false,
  "data": "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}"
}

$.ajax(settings).done(function (response) {
  console.log(response);
});
var request = require("request");

var options = { method: 'PATCH',
  url: 'https://youraccount.auth0.com/api/v2/users/user_id',
  headers: 
   { 'content-type': 'application/json',
     authorization: 'Bearer YOUR_TOKEN' },
  body: { user_metadata: { addresses: { home: '123 Main Street, Anytown, ST 12345' } } },
  json: true };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(body);
});
#import <Foundation/Foundation.h>

NSDictionary *headers = @{ @"authorization": @"Bearer YOUR_TOKEN",
                           @"content-type": @"application/json" };
NSDictionary *parameters = @{ @"user_metadata": @{ @"addresses": @{ @"home": @"123 Main Street, Anytown, ST 12345" } } };

NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://youraccount.auth0.com/api/v2/users/user_id"]
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:10.0];
[request setHTTPMethod:@"PATCH"];
[request setAllHTTPHeaderFields:headers];
[request setHTTPBody:postData];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                if (error) {
                                                    NSLog(@"%@", error);
                                                } else {
                                                    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
                                                    NSLog(@"%@", httpResponse);
                                                }
                                            }];
[dataTask resume];
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://youraccount.auth0.com/api/v2/users/user_id",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "PATCH",
  CURLOPT_POSTFIELDS => "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}",
  CURLOPT_HTTPHEADER => array(
    "authorization: Bearer YOUR_TOKEN",
    "content-type: application/json"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
import http.client

conn = http.client.HTTPSConnection("youraccount.auth0.com")

payload = "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}"

headers = {
    'authorization': "Bearer YOUR_TOKEN",
    'content-type': "application/json"
    }

conn.request("PATCH", "/api/v2/users/user_id", payload, headers)

res = conn.getresponse()
data = res.read()

print(data.decode("utf-8"))
require 'uri'
require 'net/http'

url = URI("https://youraccount.auth0.com/api/v2/users/user_id")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Patch.new(url)
request["authorization"] = 'Bearer YOUR_TOKEN'
request["content-type"] = 'application/json'
request.body = "{\"user_metadata\": {\"addresses\": {\"home\": \"123 Main Street, Anytown, ST 12345\"}}}"

response = http.request(request)
puts response.read_body
import Foundation

let headers = [
  "authorization": "Bearer YOUR_TOKEN",
  "content-type": "application/json"
]
let parameters = ["user_metadata": ["addresses": ["home": "123 Main Street, Anytown, ST 12345"]]]

let postData = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: nil)

var request = NSMutableURLRequest(URL: NSURL(string: "https://youraccount.auth0.com/api/v2/users/user_id")!,
                                        cachePolicy: .UseProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.HTTPMethod = "PATCH"
request.allHTTPHeaderFields = headers
request.HTTPBody = postData

let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    println(error)
  } else {
    let httpResponse = response as? NSHTTPURLResponse
    println(httpResponse)
  }
})

dataTask.resume()

Note: The Auth0 Management APIv2 token is required to call the Auth0 Management API. Click here to learn more about how to get a Management APIv2 Token.