Skip to content

Commit

Permalink
fix(trpc): adding host and port env variables to nitro dev process & …
Browse files Browse the repository at this point in the history
…using them for trpc during dev

$fetch is smart enough to infer the host and port for our trpc client
when it is used on the server. However, $fetch is only available during
the pre-render phase and during SSR of the prod nitro server. It is not
available during development when we work with the vite server. This PR
adds the host & port from the vite server as env variables and uses them
as fallbacks. It also adjusts the Nx plugin's and trpc-app's vite config
files to make sure that the index page is server side rendered, but not
pre-rendered to avoid not displaying the latest data.
  • Loading branch information
goetzrobin committed Oct 20, 2023
1 parent 5f6bbe6 commit 7df4901
Show file tree
Hide file tree
Showing 7 changed files with 51 additions and 17 deletions.
10 changes: 7 additions & 3 deletions apps/trpc-app-e2e-playwright/tests/app.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,16 +44,20 @@ describe('tRPC Demo App', () => {
});

test<TRPCTestContext>(`
If user enters the first note the note should be storedsuccessfully and listed in the notes array.
Still unauthorized the user should not be able to delete the note and the error should be displayed.
After the users clicks the Login button and gets authorized, deleting the note again should work successfully,
If user enters the first note the note should be stored successfully and listed in the notes array.
After reloading the page, the first note should show immediately, as the page is server side rendered.
Still unauthorized, the user should not be able to delete the note and the error should be displayed.
After the users clicks the "Login" button and gets authorized, deleting the note again should work successfully,
and the error should disappear.
`, async (ctx) => {
await ctx.notesPage.typeNote(notes.first.note);

await ctx.notesPage.addNote();
expect(await ctx.notesPage.notes().elementHandles()).toHaveLength(1);

await ctx.notesPage.page.reload();
expect(await ctx.notesPage.notes().elementHandles()).toHaveLength(1);

await ctx.notesPage.removeNote(0);
expect(await ctx.notesPage.notes().elementHandles()).toHaveLength(1);
expect(await ctx.notesPage.getDeleteErrorCount()).toBe(1);
Expand Down
13 changes: 7 additions & 6 deletions apps/trpc-app/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,19 @@ export default defineConfig(({ mode }) => {
include: ['@angular/common', '@angular/forms', 'isomorphic-fetch'],
},
ssr: {
noExternal: '@analogjs/trpc',
noExternal: ['@analogjs/trpc', '@trpc/server'],
},
build: {
target: ['es2020'],
},
plugins: [
analog({
vite: {
inlineStylesExtension: 'css',
},
prerender: {
routes: ['/'],
nitro: {
routeRules: {
'/': {
prerender: false,
},
},
},
}),
nxViteTsPaths(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,27 @@ export default defineConfig(({ mode }) => {
return {
publicDir: 'src/public',
<% if (addTRPC) { %>
server: {
host: '127.0.0.1'
},
ssr: {
noExternal: '@analogjs/trpc/**',
noExternal: ['@analogjs/trpc','@trpc/server'],
},
<% } %>
build: {
target: ['es2020'],
},
plugins: [
<% if (addTRPC) { %>
analog({
nitro: {
routeRules: {
'/': {
prerender: false,
}
}
}
}),
<% } else { %>
analog(),
<% } %>
tsConfigPaths({
root: '<%= offsetFromRoot %>',
}),
Expand Down
4 changes: 1 addition & 3 deletions packages/trpc/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@
"isomorphic-fetch": "^3.0.0",
"superjson": "^1.12.3"
},
"dependencies": {
"tslib": "^2.3.0"
},
"dependencies": {},
"ng-update": {
"packageGroup": [
"@analogjs/astro-angular",
Expand Down
15 changes: 15 additions & 0 deletions packages/trpc/src/lib/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,21 @@ function customFetch(
json: () => Promise.resolve(response._data),
}));
}

// dev server trpc for analog & nitro
if (typeof window === 'undefined') {
const host =
process.env['NITRO_HOST'] ?? process.env['ANALOG_HOST'] ?? 'localhost';
const port =
process.env['NITRO_PORT'] ?? process.env['ANALOG_PORT'] ?? 4205;
const base = `http://${host}:${port}`;
if (input instanceof Request) {
input = new Request(base, input);
} else {
input = new URL(input, base);
}
}

return fetch(input, init);
}

Expand Down
2 changes: 1 addition & 1 deletion packages/trpc/tsconfig.lib.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"declaration": true,
"declarationMap": true,
"inlineSources": true,
"types": []
"types": ["node"]
},
"exclude": ["src/**/*.spec.ts", "jest.config.ts", "src/**/*.test.ts"],
"include": ["src/**/*.ts"]
Expand Down
7 changes: 7 additions & 0 deletions packages/vite-plugin-nitro/src/lib/vite-plugin-nitro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,13 @@ export function nitro(options?: Options, nitroOptions?: NitroConfig): Plugin[] {
toNodeListener(server.app as unknown as App)
);

viteServer.httpServer?.once('listening', () => {
process.env['ANALOG_HOST'] = !viteServer.config.server.host
? 'localhost'
: (viteServer.config.server.host as string);
process.env['ANALOG_PORT'] = `${viteServer.config.server.port}`;
});

console.log(
`\n\nThe server endpoints are accessible under the "${apiPrefix}" path.`
);
Expand Down

0 comments on commit 7df4901

Please sign in to comment.