Unable to start Next 13 app directory (beta) in production mode - next.js

Step 1: Automatically create a new Next.js project using the new beta app directory:
npx create-next-app#latest --experimental-app
pages/api/hello.ts
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next'
type Data = {
name: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
res.status(200).json({ name: 'John Doe' })
}
This file is identical to the one created automatically created by npx - there are no modifications.
I am trying to build a simple home page, which fetches data from the api which gets data from my database. Either way an await/async will be required. I am following the instructions from here.
In this example I will demonstrate that even awaiting the supplied hello api can't seem to run in production, and I can't work out why.
app/page.tsx
async function getHelloAsync() {
const res = await fetch('http://localhost:3000/api/hello', { cache: 'no-store' });
// The return value is *not* serialized
// You can return Date, Map, Set, etc.
// Recommendation: handle errors
if (!res.ok) {
// This will activate the closest `error.js` Error Boundary
throw new Error('Failed to fetch data');
}
return res.json();
}
export default async function Page() {
const hello = await getHelloAsync();
return (
<main>
<h1>Hello: {hello.name}</h1>
</main>
)
}
To test the hello api works, I confirm that running pn run dev and then curl http://localhost:3000/api/hello the following successful response is received:
{"name":"John Doe"}
Next up we exit the dev server and run:
pn run build
The first headache is that the build will completely fail to build unless one adds { cache: 'no-store' } to the fetch command:
const res = await fetch('http://localhost:3000/api/hello', { cache: 'no-store' });
or adds this to the top of app/page.tsx:
export const fetchCache = 'force-no-store';
I am actually not sure how one would even build this if you wanted to cache the response or use revalidate instead and provide an initial optimistic response, because without cache: no-store it refuses to build outright. Ideally instead it should just cache the result from /api/hello and not fail. Running the dev server at the same idea as doing the build does allow the build to work, but then as soon as you exit the dev server and run pn run start then all the api calls fail anyway. So that is not a good idea.
This leads us to the next problem - why are the api calls not working in production (i.e. when calling pn run start).
Step 2:
pn run build
pn run start
Confirm that the following still works and yes it does:
curl http://localhost:3000/api/hello
Result:
{"name":"John Doe"}
Now we visit http://localhost:3000 in a browser but, surprise! We get the following error:
> next start
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
warn - You have enabled experimental feature (appDir) in next.config.js.
warn - Experimental features are not covered by semver, and may cause unexpected or broken application behavior. Use at your own risk.
info - Thank you for testing `appDir` please leave your feedback at https://nextjs.link/app-feedback
(node:787) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
TypeError: fetch failed
at Object.fetch (node:internal/deps/undici/undici:11118:11)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async getHelloAsync (/Users/username/nextjstest/.next/server/app/page.js:229:17)
at async Page (/Users/username/nextjstest/.next/server/app/page.js:242:19) {
cause: Error: connect ECONNREFUSED ::1:3000
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16)
at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 3000
}
}
[Error: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.] {
digest: '3567993178'
}
Why is it saying that the connection is refused when we know the API is available? I can't get this to run at all. I know this is beta but surely the code should actually run right? How do I make this code work?
Also if anyone knows where where the logs are that I'm supposed to be accessing to see digest '3567993178' please let me know.

Related

"error - unhandledRejection: Error: listen EADDRINUSE: address already in use :::3000" when I use Slack Bolt for JavaScript with ngrok and Next.js

Background
We are developing a Slack Bot. This time we are using Bolt for JavaScript (Node.js) provided by Slack, React, Next.js, and ngrok. Here is what each of them does.
Bolt for JavaScript: I don't want to use Slack's bare-bones API, but want to benefit from the function that wraps it.
React: Needed to use Next.js
Next.js: Slack needs a request URL to notify my bot app when events such as mentions occur in Slack, but Next.js makes it easy to create an API endpoint to be set to that URL (e.g. /api/something)
ngrok: In the local development environment, that URL will be http://localhost:3000, so the protocol will be http instead of https. Slack does not allow this, so we need a URL that starts with https that tunnels to the local http://localhost:3000. ngrok provides that easily!
Problem to be solved.
I have already confirmed that if I type #xxxx in a certain workspace in Slack, the event is notified to https://xxxx.jp.ngrok.io/api/slack/events. However, in this API file
app.event("app_mention", async ({ event, say }) => {
.
.
.
}
is not invoked and the following error occurs
error - unhandledRejection: Error: listen EADDRINUSE: address already in use :::3000
I would like to know why and how to resolve this.
Source code
/api/slack/events.ts
import type { NextApiRequest, NextApiResponse } from "next";
require("dotenv").config();
import app from "../../../config/slackAuth";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
// Unique case for Slack challenge
if (req.body.challenge) return res.status(200).json(req.body);
// Subscribe to 'app_mention' event in your App config
// See https://api.slack.com/tutorials/tracks/responding-to-app-mentions
app.event("app_mention", async ({ event, say }) => {
try {
// Response to the message in the thread where the event was triggered with #${message.user}
// See https://slack.dev/bolt-js/concepts#message-sending
await say({
text: `Hi <#${event.user}>!`,
thread_ts: event.ts,
});
} catch (error) {
await say({
text: `<#${event.user}> ${error.message}.`, // #userName Request failed with status code 429.
thread_ts: event.ts,
});
}
});
(async () => {
// Start this app
await app.start(process.env.PORT || 3000);
console.log("⚡️ Bolt app is running!");
})();
return res.status(404).json({ message: "Unknown event type" });
}
Error code
error - unhandledRejection: Error: listen EADDRINUSE: address already in use :::3000
at Server.setupListenHandle [as _listen2] (net.js:1331:16)
at listenInCluster (net.js:1379:12)
at Server.listen (net.js:1465:7)
at C:\Users\81906\Documents\slackGpt3\node_modules\#slack\bolt\dist\receivers\HTTPReceiver.js:176:25
at new Promise (<anonymous>)
at HTTPReceiver.start (C:\Users\81906\Documents\slackGpt3\node_modules\#slack\bolt\dist\receivers\HTTPReceiver.js:142:16)
at App.start (C:\Users\81906\Documents\slackGpt3\node_modules\#slack\bolt\dist\App.js:241:30)
at eval (webpack-internal:///(api)/./pages/api/slack/events.ts:69:69)
at handler (webpack-internal:///(api)/./pages/api/slack/events.ts:71:7)
at Object.apiResolver (C:\Users\81906\Documents\slackGpt3\node_modules\next\dist\server\api-utils\node.js:363:15) {
code: 'EADDRINUSE',
errno: -4091,
syscall: 'listen',
address: '::',
port: 3000
}
Issue
Using Slack Bolt for JavaScript with Next.js is not straightforward due to the following reasons:
Running npm run dev in a Next.js project starts a server at localhost:3000.
Running app.start() in Slack Bolt for JavaScript starts a server using Express.js, which also tries to use localhost:3000.
This causes an error because two servers are trying to use the same port.
This information was provided by someone at Slack, and the source can be found at https://github.com/slackapi/bolt-js/issues/1687.
Solution
You can change the port number used by Bolt to, for example, 3001.
However, this will make it difficult for the two servers at localhost:3000 and 3001 to communicate with each other.
The request URL registered in the Slack Bolt for JavaScript console is set to 3000, so events received there will not be able to flow to port 3001.

SvelteKit fetch Request to Authenticated CloudKit API Fails

I have a simple GET request to one of Apple's APIs (CloudKit) and it doesn't work in SvelteKit. The request is structured like this (line breaks added to make it easier to read):
https://api.apple-cloudkit.com/database/1/iCloud.com.MyAppContainer
/development/public/users/current?
ckAPIToken=abc
&ckWebAuthToken=xyz
If I run this request using cURL or in an API testing app like Paw, it works great:
==== Result ====
Status code: 200
================
{
"userRecordName" : "_abc123"
}
If I do the same request in SvelteKit in the client side, it returns the error the CloudKit API gives when you don't include a ckWebAuthToken, but I've definitely included it.
<script>
let url = 'https://api.apple-cloudkit.com/database/1/iCloud.com.MyAppContainer
/development/public/users/current?ckAPIToken=abc&ckWebAuthToken=xyz'
let res = await fetch(url)
console.log(await res.json())
</script>
==== Result ====
Status code: 421
================
{
uuid: 'abc...',
serverErrorCode: 'AUTHENTICATION_REQUIRED',
reason: 'request needs authorization',
redirectURL: 'https://idmsa.apple.com/IDMSWebAuth/auth?oauth_tok...'}
}
I also tried the same fetch in a server-side endpoint and the result is the same (421 error).
Is there something about fetch in SvelteKit that would make it incompatible with an external API like this?

Why do I get a "502 Gateway" error from NextJs app hosted on Firebase for POST requests only?

I started to build an API using NextJs framework. I want it to be hosted on Firebase (Hosting and Functions). Everything is working as long as I send only GET requests. When I send a POST request I receive a "502 Bad Gateway" error.
It's very simple to reproduce. You just have to download and deploy the example provided by the team developing NextJs.
create a new project on Firebase console
install the "with Firebase hosting" example
change the project name in the .firebaserc (line 3) file
create a folder "api" under the folder "pages"
create a file "hello.js" under the folder "api" and add the following snippet
export default async (req, res) => {
const {
body,
method
} = req;
console.log("method :>> ", method);
console.log("body :>> ", body);
switch (method) {
case "POST":
res.status(200).end(`Method ${method} supported!`);
break;
default:
res.setHeader("Allow", ["POST"]);
res.status(405).end(`Method ${method} Not Allowed`);
}
};
deploy the app
send a GET request to "https://[project-name].web.app/api/hello" and see it works
send a POST request to "https://[project-name].web.app/api/hello" and see it does not work
Do you have a the same error as me?
I spent 2 days to read articles, watch videos and try different configurations. You can even update the firebaseFunctions to add a console.log and see the POST request is caught by the Firebase Cloud Function but the NextJs server does not pass it to our API like it does for a GET request. It's out of my skills range...
Below the output you should have. The POST request should be answered with 200 - Method POST is supported!.
This was a real pain to track down, but after poking around myself for a while, I found that the same issue crops up for PUT and PATCH requests. Which suggested that it had something to do with the body of the request. Annoyingly, after finding that out, I stumbled across the thread of Issue #7960, where they found the same problem.
Simply put, the body of the request processed once by https.onRequest() and then nextjsHandle() tries to parse it again. Because the body was handled already, the raw-body module (within nextjsHandle()) waits indefinitely for 'data' events that will never come.
Currently, there isn't a way to turn off the body parsing done by https.onRequest(), so it must be disabled on the next.js end. Unfortunately, there isn't a global off switch for body parsing that can be added in next.config.js and it must be done for each and every API route (the files in pages/api) (which may change if the proposed fix in PR #16169 is added).
To disable body parsing for a given route, you add the following to the route's file
export const config = {
api: {
// disables call to body parsing module
bodyParser: false,
}
};
However, as mentioned in Issue #7960 by #rscotten, you might also want to use next dev while developing your app, so you need to enable it while using next dev but disable it while deployed. This can be done using
export const config = {
api: {
// disables call to body parsing module while deployed
bodyParser: process.env.NODE_ENV !== 'production',
}
};
Applying these changes to hello.js gives:
export default async (req, res) => {
const {
body,
method
} = req;
console.log("method :>> ", method);
console.log("body :>> ", body);
switch (method) {
case "POST":
res.status(200).end(`Method ${method} supported!`);
break;
default:
res.setHeader("Allow", ["POST"]);
res.status(405).end(`Method ${method} Not Allowed`);
}
};
export const config = {
api: {
// disable nextjs's body parser while deployed
// (as body parsing is handled by `https.onRequest()`),
// but enable it for local development using `next dev`
bodyParser: process.env.NODE_ENV !== 'production',
}
};

SkypeSDK Video and audio issue - mediaRelayAccessToken not found

I'm having problems with adding an audio or a video service to a coversation.
The chat service works fine for me.
When I add a video or an audio service I get following error:
Error: GET /ucwa/oauth/v1/applications/113925534802/communication/mediaRelayAccessToken failed: 404
{
[functions]: ,
__proto__: { },
code: "RequestFailed",
description: "GET /ucwa/oauth/v1/applications/113925534802/communication/mediaRelayAccessToken failed: 404",
message: "GET /ucwa/oauth/v1/applications/113925534802/communication/mediaRelayAccessToken failed: 404",
name: "Error",
req: { },
rsp: { },
stack: "Error: GET /ucwa/oauth/v1/applications/113925534802/communication/mediaRelayAccessToken failed: 404
at process (https://swx.cdn.skype.com/build2015/v5/SDK-build.js:8079:29)
at Anonymous function (https://swx.cdn.skype.com/build2015/v5/SDK-build.js:8018:29)
at Anonymous function (https://swx.cdn.skype.com/build2015/v5/SDK-build.js:1714:25)
at map (https://swx.cdn.skype.com/build2015/v5/SDK-build.js:1331:25)
at decompose (https://swx.cdn.skype.com/build2015/v5/SDK-build.js:8017:25)
at Anonymous function (https://swx.cdn.skype.com/build2015/v5/SDK-build.js:8007:29)
at handle (https://swx.cdn.skype.com/build2015/v5/SDK-build.js:2220:33)
at Anonymous function (https://swx.cdn.skype.com/build2015/v5/SDK-build.js:698:25)"
}
The Skype For Business Plugin is installed and works fine.
A Skype Edge server is currently not installed.
I'm using Internet Explorer 11.
The error occurs with the Skype Web SDK On Prem Sample from Microsoft as well as on my own website.
When I try to add video or audio for the second time to the same conversation i dont get any error message at all, but it still doesn't work. The request doesnt show up in the dev tools nor in fiddler. I'm using the latest version of the Skype SDk bootstrapper.
Both clients and server are in the same subnet.
Thanks in advance.
I encountered the same problem. Not sure how it happens, but the sdk has troubles to fetch or apply the media config.
You can use the this workaround:
Following line 18,892 in the debug version of the sdk, comment out both calls:
uninit();
throw error;
in the function init() of the section MediaConfig. Resulting in:
function init() {
pcMediaConfig = mediaPlugin.createComponent({
type: 'MediaPlatformConfig',
hide: true,
inproc: false
});
pcMediaConfig.event(onPluginComponentEvent);
pcMediaConfig.state.changed(function (state) {
log('pcMediaConfig.state = ' + state);
});
var p = pcMediaConfig.load().then(getMediaConfig).then(setMediaConfig).then(null, function (error) {
log('MediaConfig::init rejected');
//uninit();
//throw error;
});
return p;
}
Therefore you have to download the bootstrapper and the sdk to permanently apply the patch. To do this just fetch both in the debug version (bootstrapper version 1.2.5) and replace in function onConfig(config) line 48
}, config.corsScript && (scriptAttributes.crossOrigin = ""), loader.loadScript(getPackageUrl(config), null, handleError, scriptAttributes);
with
}, config.corsScript && (scriptAttributes.crossOrigin = ""), loader.loadScript("./scripts/SkypeSDK.js", null, handleError, scriptAttributes);
or your equivalent path
This is currently a limitation of the Skype Web SDK: it has a dependency on the mediaRelayAccessToken to proceed with audio/video calls. The dev team is aware of this issue and it may be fixed in a future release of Skype Web SDK.
The hacky way recommended above is basically to allow the SDK to continue the call upon missing mediaRelayAccessToken, so it may let you bypass the issue.
The media relay access token is returned by an edge server, so you may also try to deploy an edge server to work around this issue.

meteor-testing tutorial fails

I started the meteor-testing tutorial, but the 2nd automatic generated test fails with:
TypeError: Cannot call method 'url' of undefined
So it seems that the client variable is not defined. Did anybody experience similar issues? (btw is there a way to debug this)
i'm using ubuntu 14.04 with
Meteor 1.2.0.2
node v4.0.0
xolvio:cucumber 0.19.4_1 CucumberJS for Velocity
Update:
Generated test code intests/cucumber/features/step_definitions/sample_steps.js:
// You can include npm dependencies for support files in tests/cucumber/package.json
var _ = require('underscore');
module.exports = function () {
// You can use normal require here, cucumber is NOT run in a Meteor context (by design)
var url = require('url');
// 1st TEST OK
this.Given(/^I am a new user$/, function () {
server.call('reset'); // server is a connection to the mirror
});
// 2nd TEST FAIL
this.When(/^I navigate to "([^"]*)"$/, function (relativePath) {
// process.env.ROOT_URL always points to the mirror
client.url(url.resolve(process.env.ROOT_URL, relativePath));
});
...
};
I was said to file an issue in the chimp repository, where I was pointed to the solution:
// 2nd TEST FAIL
this.When(/^I navigate to "([^"]*)"$/, function (relativePath) {
// REPLACE client with browser
browser.url(url.resolve(process.env.ROOT_URL, relativePath));
});
This is a short fix, but I'm not sure whether you should later rather use client (seems to be wrapper for different environments).
**Update: ** meanwhile this was fixed, no adaption necessary anymore

Resources