Search code examples
javascriptnuxt.jsplaywrightnuxt3.js

Running server-side code once (at dev & build) then using the data in client-side


** Updated with nitro plugin approach **

I'm using Playwright server-side to get some data from a page that I want to use in my frontend, this the setup using nitro plugin

  • Base Project Structure

    pages
      index.vue
    server
      db
        index.js
      plugins
        playwright.js
      routes
        playwright.js
    ...
    
  • server/db/index.js

    export const db = [];
    
  • server/routes/playwright.js

    import { db } from '../db';
    export default defineEventHandler(() => db);
    
  • server/plugins/playwright.js

    import { chromium } from 'playwright';
    
    
    export default defineNitroPlugin(async () => { 
      const browser = await chromium.launch();
      // ...
      // some operations goes here
      // and some console logs for tracking progress
      // ...
      db.push(results); // results is the scraped data
    });
    

On running nuxt dev, the script in plugins/playwright starts, opens the browser, scrape the data and store it to db with all my console.log logged to the terminal (this is different in prod).

When I open local host I get the index page with the fetched data from db with no errors.

However on running nuxt generate the CLI runs as usual and I see only some of the console.logs printed to terminal as following

yarn run v1.22.19
$ nuxt generate
Nuxi 3.0.0
Nuxt 3.0.0 with Nitro 1.0.0  

WARN  Using experimental payload extraction for full-static output. 
You can opt-out by setting experimental.payloadExtraction to false. 

i Client built in 1666ms
i Building server...  
√ Server built in 581ms
√ Generated public .output/public
i Initializing prerenderer
🎭 Starting Playwright server plugin
⚙️ Read User-specifed options
📄 Initiating a new page
// There are more console.logs than these three 
i Prerendering 3 initial routes with crawler

  ├─ / (290ms)
  ├─ /200.html (3ms)
  ├─ /404.html (5ms)
  ├─ /_payload.js (2ms)
√ You can now deploy .output/public to any static hosting!
Done in 6.21s.
 *  Terminal will be reused by tasks, press any key to close it. 

On running nuxt preview and openning local host I get the index page with a an empty array (the initial value for db)

Do I need to somehow force the generate command to wait until the nitro plugin finish executing? and how can I do that?


Solution

  • The problem was in playwright package not in nuxt itself, after getting playwright to work and using routes the app worked correctly