ellandor
ellandor

Reputation: 89

How to import fs on the server side

I'm trying to send an ssr page containing the contents of a txt file, however I'm stuck on the part of being able to import the fs.

I understand that I need to be on the server side to be able to import the fs, I tried to use this code, without success

// pages/index.js

import fs from 'fs'

export async function getServerSideProps(ctx) {
    return {
        props: {}
    }
}

export default function Home() {
    return (
        <h1>...</h1>
    )
}

Upvotes: 1

Views: 1548

Answers (1)

felixmosh
felixmosh

Reputation: 35473

You can use import() or require() syntax inside getServerProps.

// pages/index.js
export async function getServerSideProps(ctx) {
  const fs = await import('fs');
  // or
  const fs = require('fs');

  return {
    props: {},
  };
}

export default function Home() {
  return <h1>...</h1>;
}

Upvotes: 1

Related Questions