Securely handle sensitive data at rest, in-transit, and in-use with the Skyflow SDK for Node.js, Deno, Bun, and Cloudflare Workers.
- Skyflow Node.js SDK
- Table of contents
- Overview
- Installation
- Quickstart
- Upgrade from v1 to v2
- Vault
- Detect
- Connections
- Authentication & authorization
- Logging
- Error handling
- Security
The Skyflow SDK enables you to connect to your Skyflow Vault(s) to securely handle sensitive data at rest, in-transit, and in-use.
Important
This readme documents SDK version 2.
For version 1 see the v1.14.2 README.
For more information on how to migrate see MIGRATE_TO_V2.md.
Requires Node v12.22.12 and above.
npm install skyflow-nodeDepending on your project setup, you may use either the require method (common in Node.js projects) or the import statement (common in projects using ES modules).
const{ Skyflow }=require("skyflow-node");import{Skyflow}from"skyflow-node";import{Skyflow,// Vault clientisExpired,// JWT auth helpersLogLevel,// logging options}from"skyflow-node";Get started quickly with the essential steps: authenticate, initialize the client, and perform a basic vault operation. This section shows you a minimal working example.
You can use an API key or a personal bearer token to directly authenticate and authorize requests with the SDK. Use API keys for long-term service authentication. Use bearer tokens for optimal security.
import{Credentials}from'skyflow-node';constcredentials: Credentials={apiKey: "<API_KEY>",};import{Credentials}from'skyflow-node';constcredentials: Credentials={token: "<BEARER_TOKEN>",};For authenticating via generated bearer tokens including support for scoped tokens, context-aware access tokens, and more, refer to the Authentication & Authorization section.
Initialize the Skyflow client first. You can specify different credential types during initialization.
import{Skyflow,SkyflowConfig,VaultConfig,Env,LogLevel}from'skyflow-node';// Create a credentials object. We'll use an API key.constskyflowCredentials={apiKey: "<SKYFLOW_API_KEY>"};// Configure vaultconstvaultConfig: VaultConfig={vaultId: '<VAULT_ID>',clusterId: '<CLUSTER_ID>',env: Env.PROD};// Initialize Skyflow clientconstskyflowConfig: SkyflowConfig={vaultConfigs: [vaultConfig],skyflowCredentials: skyflowCredentials,logLevel: LogLevel.ERROR};constskyflowClient: Skyflow=newSkyflow(skyflowConfig);See docs/advanced_initialization.md for advanced initialization examples including multiple vaults and different credential types.
Insert data into your vault using the insert method. Set insertOptions.setReturnTokens(true) to ensure values are tokenized in the response.
Create an insert request with the InsertRequest class, which includes the values to be inserted as a list of records.
Below is a simple example to get started. See the Insert and tokenize data section for advanced options.
import{InsertRequest,InsertOptions}from"skyflow-node";// Insert sensitive data into the vaultconstinsertData=[{card_number: "4111111111111112",cardholder_name: "John Doe"},];constinsertReq=newInsertRequest("table1",insertData);constinsertOptions=newInsertOptions();insertOptions.setReturnTokens(true);constinsertResponse=awaitskyflowClient.vault(vaultId).insert(insertReq,insertOptions);console.log("Insert response:",insertResponse);Upgrade from skyflow-node v1 using the dedicated guide in docs/migrate_to_v2.md.
The Vault performs operations on the vault such as inserting records, detokenizing tokens, retrieving tokens for list of skyflow_id's and to invoke the Connection.
Pass options to the insert method to enable additional functionality such as returning tokenized data, upserting records, or allowing bulk operations to continue despite errors. See Quickstart for a basic example.
import{InsertRequest,InsertResponse}from'skyflow-node';constinsertRequest=newInsertRequest('table1',[{<FIELD_NAME_1>: '<VALUE_1>',<FIELD_NAME_2>: '<VALUE_2>',},{<FIELD_NAME_1>: '<VALUE_1>',<FIELD_NAME_2>: '<VALUE_2>',},]);constresponse: InsertResponse=awaitskyflowClient.vault('<VAULT_ID>').insert(insertRequest);console.log('Insert response:',response);Set the continueOnError flag to true to allow insert operations to proceed despite encountering partial errors.
Tip
See the full example in the samples directory: insert-continue-on-error.ts
Turn an insert into an 'update-or-insert' operation using the upsert option. The vault checks for an existing record with the same value in the specified column. If a match exists, the record updates; otherwise, a new record inserts.
// ...// Specify the column to use as the index for the upsert. // Note: The column must have the `unique` constraint configured in the vault.insertOptions.setUpsertColumn("cardholder_name");// ...Convert tokens back into plaintext values (or masked values) using the .detokenize() method. Detokenization accepts tokens and returns values.
Create a detokenization request with the DetokenizeRequest class, which requires a list of tokens and column groups as input.
Provide optional parameters such as the redaction type and the option to continue on error.
import{DetokenizeOptions,DetokenizeRequest,DetokenizeResponse,}from"skyflow-node";constdetokenizeRequest=newDetokenizeRequest([{token: "token1",redactionType: RedactionType.PLAIN_TEXT},{token: "token2",redactionType: RedactionType.PLAIN_TEXT},]);constdetokenizeOptions=newDetokenizeOptions();detokenizeOptions.setContinueOnError(true);detokenizeOptions.setDownloadURL(false);constresponse: DetokenizeResponse=awaitskyflowClient.vault(primaryVaultConfig.vaultId).detokenize(detokenizeRequest,detokenizeOptions);console.log("Detokenization response:",response);Tip
See the full example in the samples directory: detokenzie-records.ts
Retrieve data using Skyflow IDs or unique column values with the get method. Create a get request with the GetRequest class, specifying parameters such as the table name, redaction type, Skyflow IDs, column names, and column values.
Note
You can't use both Skyflow IDs and column name/value pairs in the same request. Use the GetOptions class to specify whether to return tokens.
import{GetRequest,GetOptions,GetResponse}from"skyflow-node";constgetRequest=newGetRequest("table1",["<SKYFLOW_ID1>","<SKYFLOW_ID2>"]);constgetOptions=newGetOptions();getOptions.setReturnTokens(false);constresponse: GetResponse=awaitskyflowClient.vault("<VAULT_ID>").get(getRequest,getOptions);console.log("Get response:",response);Retrieve specific records using Skyflow IDs. Use this method when you know the exact record IDs.
import{GetOptions,GetRequest,SkyflowError,GetResponse,RedactionType,}from"skyflow-node";// Initialize a list of Skyflow IDs to retrieve records (replace with actual Skyflow IDs)constgetIds: Array<string>=["a581d205-1969-4350-acbe-a2a13eb871a6","5ff887c3-b334-4294-9acc-70e78ae5164a",];// Step 2: Create a GetRequest to retrieve records by Skyflow IDconstgetRequest: GetRequest=newGetRequest("table1",// Replace with your actual table namegetIds,);// Step 3: Configure Get Options and specify not to return tokens and redaction typeconstgetOptions: GetOptions=newGetOptions();getOptions.setReturnTokens(false);// Optional: Set to false to avoid returning tokensgetOptions.setRedactionType(RedactionType.PLAIN_TEXT);// Step 4: Send the request to the Skyflow vault and retrieve the recordsconstgetResponse: GetResponse=awaitskyflowClient.vault(primaryVaultConfig.vaultId).get(getRequest,getOptions);// Replace <VAULT_ID> with your actual Skyflow vault IDconsole.log("Data retrieval successful:",getResponse);Return tokens for records to securely process sensitive data while maintaining data privacy.
getOptions.setReturnTokens(true);// Set to `true` to get tokensTip
See the full example in the samples directory: get-records.ts
Retrieve records by unique column values when you don't know the Skyflow IDs. Use this method to query data with alternate unique identifiers.
constgetRequest: GetColumnRequest=newGetColumnRequest(tableName,columnName,columnValues,// Column values of the records to return);Tip
See the full example in the samples directory: get-column-values.ts
Use redaction types to control how sensitive data displays when retrieved from the vault.
Available Redaction Types
DEFAULT: Applies the vault-configured default redaction setting.REDACTED: Completely removes sensitive data from view.MASKED: Partially obscures sensitive information.PLAIN_TEXT: Displays the full, unmasked data.
Choosing the Right Redaction Type
- Use
REDACTEDfor scenarios requiring maximum data protection to prevent exposure of sensitive information. - Use
MASKEDto provide partial visibility of sensitive data for less critical use cases. - Use
PLAIN_TEXTfor internal, authorized access where full data visibility is necessary.
Update data in your vault using the update method. Create an update request with the UpdateRequest class, specifying parameters such as the table name and data (as a dictionary).
Configure update options using the UpdateOptions class to control returnTokens, tokens, and tokenMode. When returnTokens is true, Skyflow returns tokens for the updated records. When false, Skyflow returns IDs for the updated records.
import{UpdateRequest,UpdateResponse}from'skyflow-node';constupdateRequest=newUpdateRequest('table1',{skyflowId: '<SKYFLOW_ID>',<COLUMN_NAME_1>: '<COLUMN_VALUE_1>',<COLUMN_NAME_2>: '<COLUMN_VALUE_2>'});constresponse: UpdateResponse=awaitskyflowClient.vault('<VAULT_ID>').update(updateRequest);console.log('Update response:',response);Tip
See the full example in the samples directory: update-record.ts
Delete records using Skyflow IDs with the delete method. Create a delete request with the DeleteRequest class, which accepts a list of Skyflow IDs:
import{DeleteRequest,DeleteResponse}from"skyflow-node";constdeleteRequest=newDeleteRequest("table1",["<SKYFLOW_ID1>","<SKYFLOW_ID2>","<SKYFLOW_ID3>",]);constresponse: DeleteResponse=awaitskyflowClient.vault("<VAULT_ID>").delete(deleteRequest);console.log("Delete response:",response);Tip
See the full example in the samples directory: delete-records.ts
Retrieve data with SQL queries using the query method. Create a query request with the QueryRequest class, which takes the query parameter as follows:
import{QueryRequest,QueryResponse}from"skyflow-node";constqueryRequest=newQueryRequest("SELECT * FROM table1 WHERE column1 = 'value'",);constresponse: QueryResponse=awaitskyflowClient.vault("<VAULT_ID>").query(queryRequest);console.log("Query response:",response);Tip
See the full example in the samples directory: query-records.ts
Refer to Query your data and Execute Query for guidelines and restrictions on supported SQL statements, operators, and keywords.
Upload files to a Skyflow vault using the uploadFile method. Create a file upload request with the FileUploadRequest class, which accepts parameters such as the table name, column name, and Skyflow ID. Configure upload options with the FileUploadOptions class, which accepts the file object as shown below:
// Please use Node version 20 & above to run file uploadimport{FileUploadRequest,FileUploadResponse,FileUploadOptions,SkyflowError,}from"skyflow-node";import*asfsfrom"fs";// Prepare File Upload DataconsttableName: string="table-name";// Table nameconstskyflowId: string="skyflow-id";// Skyflow ID of the recordconstcolumnName: string="column-name";// Column name to store fileconstfilePath: string="file-path";// Path to the file for upload// Create File Upload RequestconstuploadReq: FileUploadRequest=newFileUploadRequest(tableName,skyflowId,columnName,);// Configure FileUpload OptionsconstuploadOptions: FileUploadOptions=newFileUploadOptions();constbuffer=fs.readFileSync(filePath);// Set any one of FilePath, Base64 or FileObject in FileUploadOptionsuploadOptions.setFileObject(newFile([buffer],filePath));// Set a File object// Perform File Uploadconstresponse: FileUploadResponse=awaitskyflowClient.vault(primaryVaultConfig.vaultId).uploadFile(uploadReq,uploadOptions);console.log("File upload:",response);Tip
See the full example in the samples directory: file-upload.ts
Retrieve tokens for values that already exist in the vault using the .tokenize() method. This method returns existing tokens only and does not generate new tokens.
import{TokenizeRequest,TokenizeResponse}from"skyflow-node";consttokenizeRequest=newTokenizeRequest([{value: "<VALUE_1>",columnGroup: "<COLUMN_GROUP_1>"},{value: "<VALUE_2>",columnGroup: "<COLUMN_GROUP_2>"},]);constresponse: TokenizeResponse=awaitskyflowClient.vault("<VAULT_ID>").tokenize(tokenizeRequest);console.log("Tokenization Result:",response);Tip
See the full example in the samples directory: tokenize-records.ts
De-identify and reidentify sensitive data in text and files using Skyflow Detect, which supports advanced privacy-preserving workflows.
De-identify or anonymize text using the deidentifyText method.
Create a de-identify text request with the DeidentifyTextRequest class, which includes the text to be deidentified. Provide optional parameters using the DeidentifyTextOptions class.
import{DeidentifyTextRequest,DeidentifyTextOptions,SkyflowError,TokenFormat,TokenType,Transformations,DetectEntities,}from"skyflow-node";// Prepare the text to be deidentifiedconstdeidentifyTextRequest=newDeidentifyTextRequest("<TEXT_TO_BE_DEIDENTIFIED>",);// Configure DeidentifyTextOptionsconstoptions=newDeidentifyTextOptions();options.setEntities([DetectEntities.ACCOUNT_NUMBER,DetectEntities.SSN]);// Entities to de-identifyoptions.setAllowRegexList(["<YOUR_REGEX_PATTERN>"]);// Allowlist regex patternsoptions.setRestrictRegexList(["<YOUR_REGEX_PATTERN>"]);// Restrict regex patternsconsttokenFormat=newTokenFormat();// Specify the token format for deidentified entitiestokenFormat.setDefault(TokenType.VAULT_TOKEN);optionsText.setTokenFormat(tokenFormat);consttransformations=newTransformations();// Specify custom transformations for entitiestransformations.setShiftDays({max: 30,// Maximum shift daysmin: 30,// Minimum shift daysentities: [DetectEntities.ACCOUNT_NUMBER,DetectEntities.SSN],// Entities to apply the shift});optionsText.setTransformations(transformations);// Call deidentifyTextconstresponse=awaitskyflowClient.detect(primaryVaultConfig.vaultId).deidentifyText(deidentifyTextRequest,options);console.log("De-identify Text Response:",response);Tip
See the full example in the samples directory: deidentify-text.ts
Re-identify text using the reidentifyText method. Create a reidentify text request with the ReidentifyTextRequest class, which includes the redacted or de-identified text to be re-identified. Provide optional parameters using the ReidentifyTextOptions class to control how specific entities are returned (as redacted, masked, or plain text).
import{ReidentifyTextRequest,ReidentifyTextOptions,SkyflowError,DetectEntities,ReidentifyTextResponse,}from"skyflow-node";// Prepare the redacted text to be re-identifiedconstrequest=newReidentifyTextRequest("<REDACTED_TEXT_TO_REIDENTIFY>");// Configure ReidentifyTextOptionsconstoptions=newReidentifyTextOptions();options.setRedactedEntities([DetectEntities.SSN]);// Entities to keep redactedoptions.setMaskedEntities([DetectEntities.CREDIT_CARD_NUMBER]);// Entities to maskoptions.setPlainTextEntities([DetectEntities.NAME]);// Entities to return as plain text// Call reidentifyTextconstresponse: ReidentifyTextResponse=awaitskyflowClient.detect(primaryVaultConfig.vaultId).reidentifyText(request,options);console.log("Reidentify Text Response:",response);Tip
See the full example in the samples directory: reidentify-text.ts
De-identify files using the deidentifyFile method. Create a de-identify file request with the DeidentifyFileRequest class, which includes the file to be deidentified (such as images, PDFs, audio, documents, spreadsheets, or presentations). Provide optional parameters using the DeidentifyFileOptions class to control how entities are detected and deidentified, as well as how the output is generated for different file types.
Note
File de-identification requires Node.js v20.x or above.
import{DeidentifyFileRequest,DeidentifyFileOptions,DeidentifyFileResponseSkyflowError,DetectEntities,MaskingMethod,DetectOutputTranscription,Bleep}from'skyflow-node';// Prepare the file to be deidentifiedconstfilePath: string='<FILE_PATH>';constbuffer=fs.readFileSync(filePath);constfile=newFile([buffer],filePath);// Construct the file input by providing either a file object or file path, but not bothconstfileInput: FileInput={file: file}// OR const fileInput: FileInput = { filePath: filePath }constfileReq=newDeidentifyFileRequest(fileInput);// Configure DeidentifyFileOptionsconstoptions=newDeidentifyFileOptions();options.setEntities([DetectEntities.SSN,DetectEntities.ACCOUNT_NUMBER]);options.setAllowRegexList(['<YOUR_REGEX_PATTERN>']);options.setRestrictRegexList(['<YOUR_REGEX_PATTERN>']);consttokenFormat=newTokenFormat();// Token format for deidentified entitiestokenFormat.setDefault(TokenType.ENTITY_ONLY);options.setTokenFormat(tokenFormat);consttransformations=newTransformations();// transformations for entitiestransformations.setShiftDays({max: 30,min: 10,entities: [DetectEntities.SSN],});options.setTransformations(transformations);options.setOutputDirectory('<OUTPUT_DIRECTORY_PATH>');// Output directory for saving the deidentified file. This is not supported in Cloudflare workersoptions.setWaitTime(64);// Wait time for response (max 64 seconds; throws error if more)// Call deidentifyFileconstresponse: DeidentifyFileResponse=awaitskyflowClient.detect(primaryVaultConfig.vaultId).deidentifyFile(fileReq,options);console.log('De-identify File Response:',response);Supported file types:
- Documents:
doc,docx,pdf - PDFs:
pdf - Images:
bmp,jpeg,jpg,png,tif,tiff - Structured text:
json,xml - Spreadsheets:
csv,xls,xlsx - Presentations:
ppt,pptx - Audio:
mp3,wav
Notes:
- Transformations can't be applied to Documents, Images, or PDFs file formats.
- The
waitTimeoption must be ≤ 64 seconds; otherwise, an error is thrown. - If the API takes more than 64 seconds to process the file, it will return only the
runIdandstatusin the response.
Tip
See the full example in the samples directory: deidentify-file.ts
Retrieve the results of a previously started file de-identification operation (or 'run') using the getDetectRun(...) method. Initialize the GetDetectRunRequest class with the runId returned from a prior .deidentifyFile(fileReq, options) call. Fetch the final results of the file de-identification operation once they are available.
import{GetDetectRunRequest,DeidentifyFileResponse,DeidentifyFileResponseSkyflowError}from'skyflow-node';// Prepare the GetDetectRunRequest with the runId from a previous deidentifyFile callconstrequest=newGetDetectRunRequest({runId: '<RUN_ID_FROM_DEIDENTIFY_FILE>',// Replace with the runId you received earlier});// Step 2: Call getDetectRunconstresponse: DeidentifyFileResponse=awaitskyflowClient.detect(primaryVaultConfig.vaultId).getDetectRun(request);// Step 3: Handle the responseconsole.log('Get Detect Run Response:',response);Tip
See the full example in the samples directory: get-detect-run.ts
Securely send and receive data between your systems and first- or third-party services using Skyflow Connections, a gateway service that uses tokenization. The connections module invokes both inbound and outbound connections.
- Inbound connections: Act as intermediaries between your client and server, tokenizing sensitive data before it reaches your backend, ensuring downstream services handle only tokenized data.
- Outbound connections: Enable secure extraction of data from the vault and transfer it to third-party services via your backend server, such as processing checkout or card issuance flows.
Invoke a connection using the invoke method of the Skyflow client.
import{InvokeConnectionRequest,RequestMethod,InvokeConnectionResponse,}from"skyflow-node";constinvokeRequest=newInvokeConnectionRequest(RequestMethod.POST,{<COLUMN_NAME_1>: "<COLUMN_VALUE_1>"},{<HEADER_NAME_1>: "<HEADER_VALUE_1>"},{<PATH_PARAM_KEY_1>: "<PATH_PARAM_VALUE_1>"},{<QUERY_PARAM_KEY_1>: "<QUERY_PARAM_VALUE_1>"});constresponse: InvokeConnectionResponse=awaitskyflowClient.connection().invoke(invokeRequest);console.log("Invoke connection response:",response);The method of RequestMethod.POST must be one of:
GETPOSTPUTPATCHDELETE
pathParams, queryParams, header, body are the JSON objects represented as dictionaries that will be sent through the connection integration url.
Tip
See the full example in the samples directory: scoped-token-generation-example.ts
See docs.skyflow.com for more details on integrations with Connections, Functions, and Pipelines.
The SDK accepts one of several types of credentials object.
API keys A unique identifier used to authenticate and authorize requests to an API. Use for long-term service authentication. To create an API key, first create a 'Service Account' in Skyflow and choose the 'API key' option during creation.
constcredentials: Credentials={apiKey: "<YOUR_API_KEY>"};
Bearer tokens A temporary access token used to authenticate API requests. Use for optimal security. As a developer with the right access, you can generate a temporary personal bearer token in Skyflow in the user menu.
constcredentials: Credentials={token: "<YOUR_BEARER_TOKEN>"};
Service account credentials file path The file path pointing to a JSON file containing credentials for a service account. Use when credentials are managed externally or stored in secure file systems.
constcredentials: Credentials={path: "<YOUR_CREDENTIALS_FILE_PATH>"};
Service account credentials string JSON-formatted string containing service account credentials. Use when integrating with secret management systems or when credentials are passed programmatically.
constcredentials: Credentials={credentialsString: JSON.stringify(process.env.SKYFLOW_CREDENTIALS)};
Environment variables If no credentials are explicitly provided, the SDK automatically looks for the SKYFLOW_CREDENTIALS environment variable. Use to avoid hardcoding credentials in source code. This variable must return an object like one of the examples above.
Note
Only one type of credential can be used at a time. If multiple credentials are provided, the last one added will take precedence.
Generate and manage bearer tokens to authenticate API calls. This section covers options for scoping to certain roles, passing context, and signing data tokens.
Generate service account tokens using the Service Account Node package with a service account credentials file provided when a service account is created. Tokens generated by this module are valid for 60 minutes and can be used to make API calls to the Data and Management APIs, depending on the permissions assigned to the service account.
The generateBearerToken(filepath) function takes the credentials.json file path for token generation.
let bearerToken: string='';generateBearerToken('path/to/credentials.json').then(response=>{bearerToken=response.accessToken;// Resolve the generated Bearer Tokenresolve(bearerToken);}).catch(error=>{// Handle any errors that occur during the generation processreject(error);});Alternatively, you can also send the entire credentials as string by using generateBearerTokenFromCreds(string).
Tip
See the full example in the samples directory: token-generation-example.ts
Generate bearer tokens with access limited to a specific role by specifying the appropriate roleID when using a service account with multiple roles. Use this to limit access for services with multiple responsibilities, such as segregating access for billing and analytics. Generated bearer tokens are valid for 60 minutes and can only execute operations permitted by the permissions associated with the designated role.
constoptions={roleIDs: ['roleID1','roleID2'],};Tip
See the full example in the samples directory: scoped-token-generation-example.ts
See docs.skyflow.com for more details on authentication, access control, and governance for Skyflow.
Embed context values into a bearer token during generation so you can reference those values in your policies. This enables more flexible access controls, such as tracking end-user identity when making API calls using service accounts, and facilitates using signed data tokens during detokenization.
Generate bearer tokens containing context information using a service account with the context_id identifier. Context information is represented as a JWT claim in a Skyflow-generated bearer token. Tokens generated from such service accounts include a context_identifier claim, are valid for 60 minutes, and can be used to make API calls to the Data and Management APIs, depending on the service account's permissions.
Tip
See the full example in the samples directory: token-generation-with-context-example.ts
See docs.skyflow.com for more details on authentication, access control, and governance for Skyflow.
Digitally sign data tokens with a service account's private key to add an extra layer of protection. Skyflow generates data tokens when sensitive data is inserted into the vault. Detokenize signed tokens only by providing the signed data token along with a bearer token generated from the service account's credentials. The service account must have the necessary permissions and context to successfully detokenize the signed data tokens.
Tip
See the full example in the samples directory: signed-token-generation-example.ts
See docs.skyflow.com for more details on authentication, access control, and governance for Skyflow.
The SDK provides useful logging. By default, the logging level is set to LogLevel.ERROR. Change this by setting the logLevel in Skyflow Config while creating the Skyflow Client as shown below:
Currently, the following five log levels are supported:
DEBUG:
WhenLogLevel.DEBUGis passed, logs at all levels will be printed (DEBUG, INFO, WARN, ERROR).INFO:
WhenLogLevel.INFOis passed, INFO logs for every event that occurs during SDK flow execution will be printed, along with WARN and ERROR logs.WARN:
WhenLogLevel.WARNis passed, only WARN and ERROR logs will be printed.ERROR:
WhenLogLevel.ERRORis passed, only ERROR logs will be printed.OFF:LogLevel.OFFcan be used to turn off all logging from the Skyflow Python SDK.
Note
The ranking of logging levels is as follows: DEBUG < INFO < WARN < ERROR < OFF.
constskyflowConfig: SkyflowConfig={vaultConfigs: [vaultConfig],// Add the Vault configurationskyflowCredentials: skyflowCredentials,// Use Skyflow credentials if no token is passedlogLevel: LogLevel.INFO,// Recommended to use LogLevel.ERROR in production environment.};constskyflowClient: Skyflow=newSkyflow(skyflowConfig);Wrap your calls to the Skyflow SDK in try/catch blocks as a best practice. Use the SkyflowError type to identify errors coming from Skyflow versus general request/response errors.
try{// ...call the Skyflow SDK}catch(error){// catch an error, identify if it is a SkyflowErrorif(errorinstanceofSkyflowError){console.error("Skyflow Specific Error:",{code: error.error?.http_code,message: error.message,details: error.error?.details,});}else{console.error("Unexpected Error:",JSON.stringify(error));}}When using bearer tokens for authentication and API requests, a token may expire after verification but before the actual API call completes. This causes the request to fail unexpectedly. An error from this edge case looks like this:
message: Authentication failed. Bearer token is expired. Use a valid bearer token. See https://docs.skyflow.com/api-authentication/If you encounter this kind of error, retry the request. During the retry the SDK detects that the previous bearer token has expired and generates a new one for the current and subsequent requests.
Tip
See the full example in the samples directory: bearer-token-expiry-example.ts
See docs.skyflow.com for more details on authentication, access control, and governance for Skyflow.
If you discover a potential security issue in this project, reach out to us at security@skyflow.com.
Don't create public GitHub issues or Pull Requests, as malicious actors could potentially view them.