Skip to content

Commit

Permalink
Cookie support, replaced deprecated interceptor with handle
Browse files Browse the repository at this point in the history
Fix #2
  • Loading branch information
kirill-konshin committed Nov 4, 2024
1 parent a4b3f5e commit 6ed70f9
Show file tree
Hide file tree
Showing 8 changed files with 254 additions and 98 deletions.
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Install depencencies:
$ npm install next-electron-rsc next electron electron-builder
```

Add following to your `main.js` in Electron:
Add following to your `main.js` in Electron before you create a window:

```js
import { app, protocol } from 'electron';
Expand All @@ -28,8 +28,12 @@ const { createInterceptor } = createHandler({
localhostUrl,
protocol,
});
```

Then add this when `mainWindow` is created:

if (!isDev) createInterceptor();
```js
if (!isDev) createInterceptor({ session: mainWindow.webContents.session });
```

Configure your Next.js build in `next.config.js`:
Expand Down
43 changes: 25 additions & 18 deletions demo/src-electron/index.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import path from 'path';
import { app, BrowserWindow, Menu, protocol, shell } from 'electron';
import { app, BrowserWindow, Menu, protocol, session, shell } from 'electron';
import defaultMenu from 'electron-default-menu';
import { createHandler } from 'next-electron-rsc';

const isDev = process.env.NODE_ENV === 'development';
const debugServer = !!process.env.DEBUG_SERVER;
const appPath = app.getAppPath();
const localhostUrl = 'http://localhost:666'; // must match Next.js dev server
const localhostUrl = 'http://localhost:3000'; // must match Next.js dev server

let mainWindow;
let stopIntercept;

process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
process.env['ELECTRON_ENABLE_LOGGING'] = 'true';
Expand All @@ -21,9 +21,22 @@ const openDevTools = () => {
mainWindow.webContents.openDevTools();
};

// Next.js handler

const standaloneDir = path.join(appPath, '.next', 'standalone', 'demo');

const { createInterceptor } = createHandler({
standaloneDir,
localhostUrl,
protocol,
debug: true,
});

// Next.js handler

const createWindow = async () => {
mainWindow = new BrowserWindow({
width: isDev ? 2000 : 1000,
width: 1000,
height: 800,
webPreferences: {
contextIsolation: true, // protect against prototype pollution
Expand All @@ -33,25 +46,19 @@ const createWindow = async () => {

// Next.js handler

const standaloneDir = path.join(appPath, '.next', 'standalone', 'demo');

const { createInterceptor } = createHandler({
standaloneDir,
localhostUrl,
protocol,
debug: true,
});

if (!isDev || debugServer) {
if (debugServer) console.log(`[APP] Server Debugging Enabled, ${localhostUrl} will be intercepted`);
createInterceptor();
if (!isDev) {
console.log(`[APP] Server Debugging Enabled, ${localhostUrl} will be intercepted to ${standaloneDir}`);
stopIntercept = createInterceptor({ session: mainWindow.webContents.session });
}

// Next.js handler

mainWindow.once('ready-to-show', () => isDev && openDevTools());
mainWindow.once('ready-to-show', () => openDevTools());

mainWindow.on('closed', () => (mainWindow = null));
mainWindow.on('closed', () => {
mainWindow = null;
stopIntercept?.();
});

mainWindow.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url).catch((e) => console.error(e));
Expand Down
9 changes: 9 additions & 0 deletions demo/src/app/client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,26 @@ import Image from 'next/image';

export default function Client({ foo }) {
const [text, setText] = useState<string>();
const [cookie, setCookie] = useState<string>();

useEffect(() => {
fetch('/test', { method: 'POST', body: 'Hello from frontend!' })
.then((res) => res.text())
.then((text) => setText(text));
}, []);

useEffect(() => {
setCookie(document.cookie);
}, []);

return (
<div>
Server: {foo}, API: {text}
<br />
Cookie: {cookie}
<br />
<Image src="/image.png" width={1000} height={420} alt="Next Electron RSC" />
<br />
<img src="https://picsum.photos/1000/420" width={1000} height={420} alt="Next Electron RSC" />
</div>
);
Expand Down
20 changes: 17 additions & 3 deletions demo/src/app/test/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,21 @@
import { NextResponse as Response } from 'next/server';
import { NextRequest, NextResponse } from 'next/server';

export const dynamic = 'force-dynamic';

export async function POST(req: Request) {
return Response.json({ message: 'Hello from Next.js! in response to ' + (await req.text()) });
export async function POST(req: NextRequest) {
const iteration = parseInt(req.cookies.get('iteration')?.value, 10) || 0;

const res = NextResponse.json({ message: 'Hello from Next.js! in response to ' + (await req.text()) });

res.cookies.set('iteration', (iteration + 1).toString(), {
path: '/',
maxAge: 60 * 60, // 1 hour
});

res.cookies.set('date', Date.now().toString(), {
path: '/',
maxAge: 60 * 60, // 1 hour
});

return res;
}
8 changes: 6 additions & 2 deletions lib/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Install depencencies:
$ npm install next-electron-rsc next electron electron-builder
```

Add following to your `main.js` in Electron:
Add following to your `main.js` in Electron before you create a window:

```js
import { app, protocol } from 'electron';
Expand All @@ -28,8 +28,12 @@ const { createInterceptor } = createHandler({
localhostUrl,
protocol,
});
```

Then add this when `mainWindow` is created:

if (!isDev) createInterceptor();
```js
if (!isDev) createInterceptor({ session: mainWindow.webContents.session });
```

Configure your Next.js build in `next.config.js`:
Expand Down
7 changes: 5 additions & 2 deletions lib/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "next-electron-rsc",
"version": "0.1.5",
"version": "0.2.0",
"description": "Next.js + Electron + React Server Components",
"main": "build/index.js",
"main:src": "build/index.tsx",
Expand All @@ -15,13 +15,16 @@
},
"license": "MIT",
"dependencies": {
"resolve": "^1.22.8"
"cookie": "^1.0.1",
"resolve": "^1.22.8",
"set-cookie-parser": "^2.7.1"
},
"devDependencies": {
"@types/node": "^22.8.6",
"@types/react": "18.3.11",
"@types/react-dom": "^18.3.1",
"@types/resolve": "^1.20.6",
"@types/set-cookie-parser": "^2",
"electron": "^33.0.2",
"next": "^15.0.2",
"typescript": "^5.6.3"
Expand Down
Loading

0 comments on commit 6ed70f9

Please sign in to comment.