Axios in server side components #61431
-
Hi! I'm kinda new to next app router and I found something but while searching i couldn't find information about this |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
What error do you get? And how are you using axios in |
Beta Was this translation helpful? Give feedback.
-
I get the error too. Server Component Pages in Next.js 14.1 I get the following error when I do Does axios not support the server component of Next.js? code## src/app/axios/page.tsx
import axios from 'axios'
const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL
const instance = axios.create({baseURL: BASE_URL})
export default async function Page() {
console.log("==== axios start ====")
const res1 = await instance.get('/api/b')
const res2 = await instance.get('/api/b')
console.log(res1.data)
console.log(res2.data)
return (
<main className="text-red-500">
axios
</main>
);
} errorI [Error]: connect ECONNREFUSED ::1:3000
at I.from (/Users/hoge/Desktop/my-app/.next/server/app/axios/page.js:11:10939)
at y.<anonymous> (/Users/hoge/Desktop/my-app/.next/server/app/axios/page.js:13:8627)
at y.emit (node:events:517:28)
at d.<computed> (/Users/hoge/Desktop/my-app/.next/server/app/axios/page.js:1:16754)
at ClientRequest.emit (node:events:517:28)
at Socket.socketErrorListener (node:_http_client:501:9)
at Socket.emit (node:events:517:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
at au.request (/Users/hoge/Desktop/my-app/.next/server/app/axios/page.js:13:16923)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async av (/Users/hoge/Desktop/my-app/.next/server/app/axios/page.js:13:21719) {
port: 3000,
address: '::1',
syscall: 'connect',
code: 'ECONNREFUSED',
errno: -61,
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [ 'xhr', 'http' ],
transformRequest: [ [Function (anonymous)] ],
transformResponse: [ [Function (anonymous)] ],
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': undefined,
'User-Agent': 'axios/1.6.7',
'Accept-Encoding': 'gzip, compress, deflate, br'
},
baseURL: 'http://localhost:3000',
method: 'get',
url: '/api/b',
data: undefined
},
request: <ref *1> Writable {
_writableState: WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
afterWriteTickInfo: null,
buffered: [],
bufferedIndex: 0,
allBuffers: true,
allNoop: true,
pendingcb: 0,
constructed: true,
prefinished: false,
errorEmitted: false,
emitClose: true,
autoDestroy: true,
errored: null,
closed: false,
closeEmitted: false,
[Symbol(kOnFinished)]: []
},
_events: [Object: null prototype] {
response: [Function (anonymous)],
error: [Function (anonymous)],
socket: [Function (anonymous)]
},
_eventsCount: 3,
_maxListeners: undefined,
_options: {
maxRedirects: 21,
maxBodyLength: Infinity,
protocol: 'http:',
path: '/api/b',
method: 'GET',
headers: [Object: null prototype],
agents: [Object],
auth: undefined,
family: undefined,
beforeRedirect: [Function: e0],
beforeRedirects: [Object],
hostname: 'localhost',
port: '3000',
agent: undefined,
nativeProtocols: [Object],
pathname: '/api/b'
},
_ended: true,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 0,
_requestBodyBuffers: [],
_onNativeResponse: [Function (anonymous)],
_currentRequest: ClientRequest {
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
maxRequestsOnConnectionReached: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
strictContentLength: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
_closed: true,
socket: [Socket],
_header: 'GET /api/b HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'User-Agent: axios/1.6.7\r\n' +
'Accept-Encoding: gzip, compress, deflate, br\r\n' +
'Host: localhost:3000\r\n' +
'Connection: close\r\n' +
'\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: nop],
agent: [Agent],
socketPath: undefined,
method: 'GET',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
joinDuplicateHeaders: undefined,
path: '/api/b',
_ended: false,
res: null,
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'localhost',
protocol: 'http:',
_redirectable: [Circular *1],
[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: 'http://localhost:3000/api/b',
[Symbol(kCapture)]: false
},
cause: Error: connect ECONNREFUSED ::1:3000
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1555:16)
at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 3000
}
}
I [Error]: connect ECONNREFUSED ::1:3000
at I.from (/Users/hoge/Desktop/my-app/.next/server/app/axios/page.js:11:10939)
at y.<anonymous> (/Users/hoge/Desktop/my-app/.next/server/app/axios/page.js:13:8627)
at y.emit (node:events:517:28)
at d.<computed> (/Users/hoge/Desktop/my-app/.next/server/app/axios/page.js:1:16754)
at ClientRequest.emit (node:events:517:28)
at Socket.socketErrorListener (node:_http_client:501:9)
at Socket.emit (node:events:517:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
at au.request (/Users/hoge/Desktop/my-app/.next/server/app/axios/page.js:13:16923)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async av (/Users/hoge/Desktop/my-app/.next/server/app/axios/page.js:13:21719) {
port: 3000,
address: '::1',
syscall: 'connect',
code: 'ECONNREFUSED',
errno: -61,
config: {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: [ 'xhr', 'http' ],
transformRequest: [ [Function (anonymous)] ],
transformResponse: [ [Function (anonymous)] ],
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': undefined,
'User-Agent': 'axios/1.6.7',
'Accept-Encoding': 'gzip, compress, deflate, br'
},
baseURL: 'http://localhost:3000',
method: 'get',
url: '/api/b',
data: undefined
},
request: <ref *1> Writable {
_writableState: WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: true,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
afterWriteTickInfo: null,
buffered: [],
bufferedIndex: 0,
allBuffers: true,
allNoop: true,
pendingcb: 0,
constructed: true,
prefinished: false,
errorEmitted: false,
emitClose: true,
autoDestroy: true,
errored: null,
closed: false,
closeEmitted: false,
[Symbol(kOnFinished)]: []
},
_events: [Object: null prototype] {
response: [Function (anonymous)],
error: [Function (anonymous)],
socket: [Function (anonymous)]
},
_eventsCount: 3,
_maxListeners: undefined,
_options: {
maxRedirects: 21,
maxBodyLength: Infinity,
protocol: 'http:',
path: '/api/b',
method: 'GET',
headers: [Object: null prototype],
agents: [Object],
auth: undefined,
family: undefined,
beforeRedirect: [Function: e0],
beforeRedirects: [Object],
hostname: 'localhost',
port: '3000',
agent: undefined,
nativeProtocols: [Object],
pathname: '/api/b'
},
_ended: true,
_ending: true,
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 0,
_requestBodyBuffers: [],
_onNativeResponse: [Function (anonymous)],
_currentRequest: ClientRequest {
_events: [Object: null prototype],
_eventsCount: 7,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
destroyed: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
maxRequestsOnConnectionReached: false,
_defaultKeepAlive: true,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
strictContentLength: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
_closed: true,
socket: [Socket],
_header: 'GET /api/b HTTP/1.1\r\n' +
'Accept: application/json, text/plain, */*\r\n' +
'User-Agent: axios/1.6.7\r\n' +
'Accept-Encoding: gzip, compress, deflate, br\r\n' +
'Host: localhost:3000\r\n' +
'Connection: close\r\n' +
'\r\n',
_keepAliveTimeout: 0,
_onPendingData: [Function: nop],
agent: [Agent],
socketPath: undefined,
method: 'GET',
maxHeaderSize: undefined,
insecureHTTPParser: undefined,
joinDuplicateHeaders: undefined,
path: '/api/b',
_ended: false,
res: null,
aborted: false,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
reusedSocket: false,
host: 'localhost',
protocol: 'http:',
_redirectable: [Circular *1],
[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: 'http://localhost:3000/api/b',
[Symbol(kCapture)]: false
},
cause: Error: connect ECONNREFUSED ::1:3000
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1555:16)
at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 3000
}
}
Error occurred prerendering page "/axios". Read more: https://nextjs.org/docs/messages/prerender-error
Error: connect ECONNREFUSED ::1:3000
at I.from (/Users/hoge/Desktop/my-app/.next/server/app/axios/page.js:11:10939)
at y.<anonymous> (/Users/hoge/Desktop/my-app/.next/server/app/axios/page.js:13:8627)
at y.emit (node:events:517:28)
at d.<computed> (/Users/hoge/Desktop/my-app/.next/server/app/axios/page.js:1:16754)
at ClientRequest.emit (node:events:517:28)
at Socket.socketErrorListener (node:_http_client:501:9)
at Socket.emit (node:events:517:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
at au.request (/Users/hoge/Desktop/my-app/.next/server/app/axios/page.js:13:16923)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async av (/Users/hoge/Desktop/my-app/.next/server/app/axios/page.js:13:21719)
✓ Generating static pages (9/9)
> Export encountered errors on following paths:
/axios/page: /axios |
Beta Was this translation helpful? Give feedback.
Hi,
This is a different kind of error. ECONNREFUSED, means that there's nothing listening for the request.
This is a very well known issue, mostly created by tech-influencers, and AI generated content.
The Next.js community has written a precise explanation and set of steps to fix this problem, here:
The short explanation is that you, perhaps thinking that you have made your code modular, or DRY, but that's not correct. You've created an extra HTTP round trip requirement, which defeats the entire purpose of having co…