How to serve next js app using keystonejs? - next.js

I have a problem with serving next js app using keystonejs. I want to achive something similar like in to do nuxt example which you can choose while creating keystone project. I used code from this link https://www.keystonejs.com/keystonejs/app-next/ in index.js file, but I get an error while trying to run the app:
ReferenceError: distDir is not defined at Object.
What should I do?

this is what I have in my setup
create app folder (next js code)
create next.config.js in app folder
my next.js.config file has following code
const distDir = 'dist';
module.exports = {
distDir: `../${distDir}/www`,
env: {
SERVER_URL: process.env.SERVER_URL || 'http://localhost:4000',
},
publicRuntimeConfig: {
// Will be available on both server and client
// staticFolder: '/static',
},
};
it export the build artifacts in dist/www in root of keystone project.

Related

next js api returns no response after deployment

while working on the local host, api and the posts.jaon file also works fine. was able to perform CRUD.But after I deploy it to vercel, the api does not loads.
error in the log is something like this:
[GET] /api/insta 11:39:32:83 [Error: ENOENT: no such file or directory, open './posts.json'] { errno: -2, code: 'ENOENT', syscall: 'open', path: './posts.json' }
expecting a json response in the browser when I hit the api.
the json file is in the pages/api folder of next app.
I tried moving the json file outside pages at the top level of the folder strecture, and changing the path inside the fs("file.json",....). but nothing worked
This article from Vercel might help you:
How to Load Data from a File in Next.js
Here is an excerpt:
import path from 'path';
import { promises as fs } from 'fs';
export default async function handler(req, res) {
const jsonDirectory = path.join(process.cwd(), 'json');
const fileContents = await fs.readFile(jsonDirectory + '/data.json', 'utf8');
res.status(200).json(fileContents);
}
You would then have a folder named json where all the data is saved. That is declared in line 4. If you want to rename it, it is of course possible.

Nextjs with Jest---No tests found, exiting with code 1 Run with `--passWithNoTests` to exit with code 0

import nextJest from 'next/jest'
const createJestConfig = nextJest({
dir: './',
})
// Add any custom config to be passed to Jest
const customJestConfig = {
setupFilesAfterEnv: ['<rootDir>/setupTests.js'],
moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom',
modulePathIgnorePatterns: ['./cypress'],
// testMatch: ['<rootDir>/**/*.test.js', '<rootDir>/**/*.test.jsx'],
}
module.exports = createJestConfig(customJestConfig)
In my project, we use Nextjs application with both Cypress and Jest. The latest jest.config.ts which is recommended is shown above.
If you are now owned this problem. you can maybe try to check your modulePathIgnorePatterns.
I added a ./ to ['cypress'], then it works well. So, I think maybe it just cann't recognize the path.

pino-datadog-transport with Next.js on Vercel

I'm trying to migrate a Next.js project running on Vercel from
"pino-datadog": "2.0.2",
"pino-multi-stream": "6.0.0",
to
"pino": "8.4.2",
"pino-datadog-transport": "1.2.2",
and I copy the setup from the pino-datadog-transport's README.md:
import { LoggerOptions, pino } from 'pino'
const pinoConf: LoggerOptions = {
level: 'trace',
}
const logger = pino(
pinoConf,
pino.transport({
target: 'pino-datadog-transport',
options: {
ddClientConf: {
authMethods: {
apiKeyAuth: process.env.DATADOG_API_KEY,
},
},
ddServerConf: {
site: 'datadoghq.eu',
},
service: process.env.VERCEL_URL
ddsource: 'nodejs',
},
}),
)
and this seems to be working fine locally, but when I publish it on Vercel and run it there I get the following error:
ERROR Error: unable to determine transport target for "pino-datadog-transport"
at fixTarget (/var/task/node_modules/pino/lib/transport.js:136:13)
at Function.transport (/var/task/node_modules/pino/lib/transport.js:110:22)
Am I missing some additional config to get this working? Anyone else running this setup or something similar to get explicit logs working on Vercel with Next.js?
I have enabled the Datadog integration in Vercel as well, but that only forwards Next.js logs, not explicit console.logs or standard Pino logs from what I can tell.
The solution to this problem is to import even though nothing in the import is actually used in the code.
It seems Next.js strips away all code that isn't imported when the code is deployed.
So, adding
import 'pino-datadog-transport'
at the top of the file solves the problem.

SQL with Prisma under Electron

My Main goal is to create an Electron App (Windows) that locally stores data in an SQLite Database. And because of type safety I choose to use the Prisma framework instead of other SQLite Frameworks.
I took this Electron Sample Project and now try to include Prisma. Depending on what I try different problems do arrise.
1. PrismaClient is unable to be run in the Browser
I executed npx prisma generate and then try to execute this function via a button:
import { PrismaClient } from '#prisma/client';
onSqlTestAction(): void {
const prisma = new PrismaClient();
const newTestObject = prisma.testTable.create(
{
data: {
value: "TestValue"
}
}
);
}
When executing this in Electron I get this:
core.js:6456 ERROR Error: PrismaClient is unable to be run in the browser.
In case this error is unexpected for you, please report it in https://github.com/prisma/prisma/issues
at new PrismaClient (index-browser.js:93)
at HomeComponent.onSqlTestAction (home.component.ts:19)
at HomeComponent_Template_button_click_7_listener (template.html:7)
at executeListenerWithErrorHandling (core.js:15281)
at wrapListenerIn_markDirtyAndPreventDefault (core.js:15319)
at HTMLButtonElement.<anonymous> (platform-browser.js:568)
at ZoneDelegate.invokeTask (zone.js:406)
at Object.onInvokeTask (core.js:28666)
at ZoneDelegate.invokeTask (zone.js:405)
at Zone.runTask (zone.js:178)
It somehow seems logical that Prisma cannot run in a browser. But I actually build a native app - with Electron that embeds a Browser. It seems to be a loophole.
2. BREAKING CHANGE: webpack < 5 used to include polyfills
So i found this Question: How to use Prisma with Electron
Seemed to be exactly what I looked for. But the error message is different (Debian binaries were not found).
The solution provided is to generate the prisma artifacts into the src folder instead of node_modules - and this leads to 19 polyfills errors. One for example:
./src/database/generated/index.js:20:11-26 - Error: Module not found: Error: Can't resolve 'path' in '[PATH_TO_MY_PROJECT]\src\database\generated'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
- install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "path": false }
And this repeats with 18 other modules. Since the error message to begin with was different I also doubt that this is the way to go.
I finally figured this out. What I needed to understand was, that all Electron apps consist of 2 parts: The Frontend Webapp (running in embedded Chromium) and a Node backend server. Those 2 parts are called IPC Main and IPC Renderer and they can communicate with each other. And since Prisma can only run on the main process which is the backend I had to send my SQL actions to the Electron backend and execute them there.
My minimal example
In the frontend (I use Angular)
// This refers to the node_modules folder of the Electron Backend, the folder where the main.ts file is located.
// I just use this import so that I can use the prisma generated classes for type safety.
import { TestTable } from '../../../app/node_modules/.prisma/client';
// Button action
onSqlTestAction(): void {
this.electronService.ipcRenderer.invoke("prisma-channel", 'Test input').then((value) => {
const testObject: TestTable = JSON.parse(value);
console.log(testObject);
});
The sample project I used already had this service to provide the IPC Renderer:
#Injectable({
providedIn: 'root'
})
export class ElectronService {
ipcRenderer: typeof ipcRenderer;
webFrame: typeof webFrame;
remote: typeof remote;
childProcess: typeof childProcess;
fs: typeof fs;
get isElectron(): boolean {
return !!(window && window.process && window.process.type);
}
constructor() {
// Conditional imports
if (this.isElectron) {
this.ipcRenderer = window.require('electron').ipcRenderer;
this.webFrame = window.require('electron').webFrame;
this.childProcess = window.require('child_process');
this.fs = window.require('fs');
// If you want to use a NodeJS 3rd party deps in Renderer process (like #electron/remote),
// it must be declared in dependencies of both package.json (in root and app folders)
// If you want to use remote object in renderer process, please set enableRemoteModule to true in main.ts
this.remote = window.require('#electron/remote');
}
}
And then in the Electron backend I first added "#prisma/client": "^3.0.1" to the package.json (for the Electron backend not the frontend). Then I added to the main.ts this function to handle the requests from the renderer:
// main.ts
ipcMain.handle("prisma-channel", async (event, args) => {
const prisma = new PrismaClient();
await prisma.testTable.create(
{
data: {
value: args
}
}
);
const readValue = await prisma.testTable.findMany();
return JSON.stringify(readValue);
})
This way of simply adding the IPC Main handler in the main.ts file of course is a big code smell but usefull as minimal example. I think I will move on with the achitecture concept presented in this article.

How to connect to an existing Electron app using Spectron

Is it possible to connect to an existing Electron application using Spectron? I am not particularly sure on how to go about implementing this..
I'd like to be able to do something like:
import { Application } from 'spectron';
import electronPath from 'electron';
import path from 'path';
// but don't spawn new electron application
new Application({
path: electronPath,
args: [path.join(__dirname, '..', '..', 'app')],
});
There are some documentation out there for using debuggerAddress option in Spectron, but I'm not really sure on whether that is what I am looking for, since the arguments for debuggerAddress is url, like so: '127.0.0.1:1234'.
I struggled making this work for Electron 6, was able to in the end, here is a working repo (made changes on top of an older one)
https://github.com/florin05/electron-spectron-example
Please make sure that you have created Test Folder in the same directory and create spectron file in this file.
Json File Changes:
"scripts": {"test": "mocha"}
const app = new Application({path: electronPath,args:[path.join(__dirname,'..')],})
beforeEach(function () {return app.start()})
afterEach(function () {if (app && app.isRunning()) {return app.stop()}})

Resources