About proxy settings when using sdk

I am trying to create a function on AWS lambda to
retrieve GenesysCloud information.

However, I need to go through a proxy, and I am referring to the Using a Proxy (Node.js only) section of the following page as follows.

‐‐‐‐‐‐‐‐
const proxyUrl = process.env.HTTP_PROXY;
const client = platformClient.ApiClient.instance;
const agent = new HttpProxyAgent({
proxy: proxyUrl,
});
client.setProxyAgent(agent);
‐‐‐‐‐‐‐‐

I get the following error and do not know how to resolve it.

・TypeError [ERR_INVALID_PROTOCOL]: Protocol "https:" not supported. Expected "http:"

Hello,

const {HttpsProxyAgent} = require('hpagent')
const client = platformClient.ApiClient.instance;

agent = new HttpsProxyAgent({
  proxy: proxyUrl,
});
client.setProxyAgent(agent)

new HttpsProxyAgent and not new HttpProxyAgent

Regards,

Thanks for the info, but I wrote below, but it gave me an error.
‐‐‐‐‐‐‐‐‐‐
const{HttpsProxyAgent}= require('hpagent');
const client = platformClient.ApiClient.instance;
agent = new HttpsProxyAgent({
proxy: proxyUrl,
});
client.setProxyAgent(agent);
‐‐‐‐‐‐‐‐‐‐

I would like to know how to solve this problem.

‐‐‐‐‐‐‐‐‐
2025-02-22T15:45:44.795Z undefined ERROR Uncaught Exception {
"errorType": "Runtime.UserCodeSyntaxError",
"errorMessage": "SyntaxError: Identifier 'HttpsProxyAgent' has already been declared",
"stack": [
"Runtime.UserCodeSyntaxError: SyntaxError: Identifier 'HttpsProxyAgent' has already been declared",
" at _loadUserApp (file:///var/runtime/index.mjs:1084:17)",
" at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1119:21)",
" at async start (file:///var/runtime/index.mjs:1282:23)",
" at async file:///var/runtime/index.mjs:1288:1"
]
}
‐‐‐‐‐‐‐‐‐

I assume you did not run a file with just this code extract in it. I cannot guess/try if you don't share more. I would need to see what's the rest of your code.

Also what version of nodejs are you using?
What are you using to run this test (I mean running this on your computer? is that lambda logs?)?

I would start with checking if you have not declared the hpagent import somewhere else in your code.
Also, if you declare a file with mjs extension, it means that you want to import using ECMAScript module approach (using "import").
Using import of modules using "require" is for CommonJS modules.

Regards,

Thanks for the reply.

I am trying to create and run a function in AWS lambda.

The runtime nodejs is implemented in 20.x.

I have included the beginning of the program below.
If you have any suggestions, I would appreciate it if you could let me know.

Failure to obtain an access token.

‐‐‐‐‐‐‐‐‐‐‐

import AWS from 'aws-sdk';
import ini from 'ini';
import platformClient from 'purecloud-platform-client-v2';
import { HttpProxyAgent, HttpsProxyAgent } from 'hpagent';

const proxyUrl = process.env.HTTP_PROXY;

const{HttpsProxyAgent}= require('hpagent');
const client = platformClient.ApiClient.instance;
client.setEnvironment(platformClient.PureCloudRegionHosts.ap_northeast_1);
agent = new HttpsProxyAgent({
proxy: proxyUrl,
});
client.setProxyAgent(agent);

const tokenAPImethod = properties.GenesysSetting_Token.tokenAPImethod;
const tokenAPIURL = properties.GenesysSetting_Token.tokenAPIURL;
const TokenKigenSS = properties.GenesysSetting_Token.TokenKigenSS;



export async function runGTA001CSV() {
const token = await initialize();
}

async function initialize() {
console.log("初期処理を開始します...");
await checkLogFile();

const logLv = '[INFO ]';
const msg = 'インタラクション情報CSV作成処理 開始'; 
await logOutput(logLv, msg) 

// □ アクセストークン取得
//  ■ トークン取得
const returnToken = await getAccessToken()

console.log("初期処理完了...");
return returnToken;

}

async function getAccessToken() {
try {

    const res = await client.loginClientCredentialsGrant(clientId, clientSecret);
    const accessToken = res.accessToken;
    return accessToken;
} catch (err) {
    console.error('アクセストークンの取得に失敗しました:', err);
    const logLv = '[ERROR ]'; 
    const msg = `トークンAPI機能:${err}`; 
    await logOutput(logLv, msg);
    throw new error('処理が失敗しました');
}

}

Hello,

You have declared/imported HttpsProxyAgent twice.
Remove the second one - i.e. remove const{HttpsProxyAgent}= require('hpagent');

Regards,

1 Like

Thanks, the error about https has been cleared.

Next, I get the following error.
‐‐‐‐‐‐‐

cause: Error: Bad response: 403
at ClientRequest. (/opt/nodejs/node_modules/hpagent/index.js:106:18)
at Object.onceWrapper (node:events:634:26)
at ClientRequest.emit (node:events:519:28)
at ClientRequest.emit (node:domain:488:12)
at Socket.socketOnData (node:_http_client:584:11)
at Socket.emit (node:events:519:28)
at Socket.emit (node:domain:488:12)
at addChunk (node:internal/streams/readable:559:12)
at readableAddChunkPushByteMode (node:internal/streams/readable:510:3)
at Readable.push (node:internal/streams/readable:390:5)

Hello,

You'll have a minimum of troubleshooting to do by yourself. Sending just a stack trace whenever you reach the next error doesn't allow me or people on the forum to guess what the issue can be.

You are receiving a 403 error: I don't know on which request. You are not providing any info. First request to get the token? A Platform API endpoint that you are invoking?
If it is a token request, it is not supposed to send a 403. So it might come from your proxy.
If it is a Platform API endpoint (after token request/after authentication), that would mean that you are missing permissions assigned to your OAuth Client.

To see more logs/traces on this request and see what the response body is (which gives info on the error if it is for a Platform API endpoint), I would suggest you start enabling logging.
See here for SDK Logging

Regards,

Sorry for the lack of information.
I will post additional information below.
OAuth clients never lack privileges.
If you can tell us what you can find out, we would appreciate it.

As for the execution, we are doing the following.
This is an error in this section.
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
async function getAccessToken() {
try {
// クライアント資格情報でログイン
const res = await client.loginClientCredentialsGrant(clientId, clientSecret);
// ログイン後にアクセストークンを取得
const accessToken = res.accessToken;
return accessToken;
} catch (err) {
console.error('アクセストークンの取得に失敗しました:', err);
// ログファイルを作成する
const logLv = '[ERROR ]'; // logOutput()ログレベルメッセージ
const msg = トークンAPI機能:${err}; // logOutput()引数任意メッセージ
await logOutput(logLv, msg); // logOutput()ログ出力関数に引数を渡す
throw new error('処理が失敗しました');
}
}
‐‐‐‐‐‐‐‐‐‐‐‐‐‐
The error is as follows
The information part of Proxy and Authorization
is replaced by xxxx and information.
‐‐‐‐‐‐‐‐‐‐‐‐
2025-02-24T14:24:10.270Z ea19df68-46cb-4e3e-9c8a-1f6fda1cd957 ERROR アクセストークンの取得に失敗しました: AxiosError: Bad response: 403
at AxiosError.from (/opt/nodejs/node_modules/axios/dist/node/axios.cjs:877:14)
at RedirectableRequest.handleRequestError (/opt/nodejs/node_modules/axios/dist/node/axios.cjs:3163:25)
at RedirectableRequest.emit (node:events:519:28)
at RedirectableRequest.emit (node:domain:488:12)
at eventHandlers. (/opt/nodejs/node_modules/follow-redirects/index.js:49:24)
at ClientRequest.emit (node:events:519:28)
at ClientRequest.emit (node:domain:488:12)
at emitErrorEvent (node:_http_client:101:11)
at _destroy (node:_http_client:884:9)
at onSocketNT (node:_http_client:904:5)
at Axios.request (/opt/nodejs/node_modules/axios/dist/node/axios.cjs:4252:41)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [ 'xhr', 'http', 'fetch' ],
transformRequest: [ [Function: transformRequest] ],
transformResponse: [ [Function: transformResponse] ],
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: { FormData: [Function], Blob: [class Blob] },
validateStatus: [Function: validateStatus],
headers: Object [AxiosHeaders] {
Accept: 'application/json, text/plain, /',
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: 'Basic xxxxxxxxxxxxxxxxxxxxx=',
'User-Agent': 'axios/1.7.9',
'Content-Length': '29',
'Accept-Encoding': 'gzip, compress, deflate, br'
},
method: 'post',
url: 'https://login.mypurecloud.jp/oauth/token',
data: 'grant_type=client_credentials',
httpsAgent: HttpsProxyAgent {
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: [Object: null prototype],
requests: [Object: null prototype] {},
sockets: [Object: null prototype],
freeSockets: [Object: null prototype] {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
scheduling: 'lifo',
maxTotalSockets: Infinity,
totalSocketCount: 0,
maxCachedSessions: 100,
_sessionCache: [Object],
proxy: URL {},
proxyRequestOptions: {},
[Symbol(shapeMode)]: false,
[Symbol(kCapture)]: false
}
},
request: <ref *1> Writable {
_events: {
close: undefined,
error: [Function: handleRequestError],
prefinish: undefined,
finish: undefined,
drain: undefined,
response: [Function: handleResponse],
socket: [Function: handleRequestSocket]
},
_writableState: WritableState {
highWaterMark: 16384,
length: 0,
corked: 0,
onwrite: [Function: bound onwrite],
writelen: 0,
bufferedIndex: 0,
pendingcb: 0,
[Symbol(kState)]: 17580812,
[Symbol(kBufferedValue)]: null
},
_maxListeners: undefined,
_options: {
maxRedirects: 21,
maxBodyLength: Infinity,
protocol: 'https:',
path: 'https://login.mypurecloud.jp/oauth/token',
method: 'POST',
headers: [Object: null prototype],
agents: [Object],
auth: undefined,
family: undefined,
beforeRedirect: [Function: dispatchBeforeRedirect],
beforeRedirects: [Object],
hostname: 'xxxxxx',
port: '8080',
agent: [HttpsProxyAgent],
nativeProtocols: [Object],
pathname: 'https://login.mypurecloud.jp/oauth/token'
},
_ended: false,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 29,
_requestBodyBuffers: [ [Object] ],
_eventsCount: 3,
_onNativeResponse: [Function (anonymous)],
_currentRequest: ClientRequest {
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
outputData: [Array],
outputSize: 448,
writable: true,
destroyed: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
maxRequestsOnConnectionReached: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
strictContentLength: false,
_contentLength: '29',
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: true,
_closed: true,
socket: null,
_header: 'POST https://login.mypurecloud.jp/oauth/token HTTP/1.1\r\n' +
'Accept: application/json, text/plain, /\r\n' +
'Content-Type: application/x-www-form-urlencoded\r\n' +
'Authorization: Basic xxxxxxxxxxxxxxxxxxxxx=\r\n' +
'User-Agent: axios/1.7.9\r\n' +
'Content-Length: 29\r\n' +
'Accept-Encoding: gzip, compress, deflate, br\r\n' +
'host: login.mypurecloud.jp\r\n' +
'Connection: close\r\n' +
'\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: nop],
agent: [HttpsProxyAgent],
socketPath: undefined,
method: 'POST',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
joinDuplicateHeaders: undefined,
path: 'https://login.mypurecloud.jp/oauth/token',
_ended: false,
res: null,
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'xxxxxx',
protocol: 'https:',
_redirectable: [Circular *1],
[Symbol(shapeMode)]: false,
[Symbol(kCapture)]: false,
[Symbol(kBytesWritten)]: 0,
[Symbol(kNeedDrain)]: false,
[Symbol(corked)]: 0,
[Symbol(kOutHeaders)]: [Object: null prototype],
[Symbol(errored)]: null,
[Symbol(kHighWaterMark)]: 16384,
[Symbol(kRejectNonStandardBodyWrites)]: false,
[Symbol(kUniqueHeaders)]: null
},
_currentUrl: 'https://login.mypurecloud.jp/oauth/token',
[Symbol(shapeMode)]: true,
[Symbol(kCapture)]: false
},
cause: Error: Bad response: 403
at ClientRequest. (/opt/nodejs/node_modules/hpagent/index.js:106:18)
at Object.onceWrapper (node:events:634:26)
at ClientRequest.emit (node:events:519:28)
at ClientRequest.emit (node:domain:488:12)
at Socket.socketOnData (node:_http_client:584:11)
at Socket.emit (node:events:519:28)
at Socket.emit (node:domain:488:12)
at addChunk (node:internal/streams/readable:559:12)
at readableAddChunkPushByteMode (node:internal/streams/readable:510:3)
at Readable.push (node:internal/streams/readable:390:5)
}